0

I have a model FooModel with 2 fields with a default value (default=xxx) and marked as blank (blank=True), I created a ModelForm(django.forms.ModelForm) using FooModel and now I want to save it after submission, so in my view I have the following code:

f = FooForm(request.POST)

if f.is_valid():
  f.save()

the problem is that in this way I get a violation exception from the database because the fields that are not rendered in the html form are not automatically inherited in the FooForm instance as I would expect... how can I include fields from the original model which should not be displayed to the user? (I don't want to render them as hidden fields!)

So far I tried 2 approaches, both failed...

  1. Specify instance in the FooForm constructor (f = FooForm(request.POST, instance=FooModel()))

  2. Create an instance of a FooModel and manually assign the auto-generated values to the form's data:

    i = FooModel()
    
    f.data.fieldA = i.fieldA
    
    f.data.fieldB = i.fieldB
    

UPDATE:

by reading the django documentation more accurately, I solved in this way:

if f.is_valid():
  formModel = f.save(commit=False)
  foo = FooModel()
  formModel.fieldA = foo.fieldA
  formModel.fieldB = foo.fieldB
  formModel.save()

but, to be honest, I'm not satisfied... I would like to abstract out the addition of those fields... perhaps by using a custom decorator... something like:

f = MissingFieldsDecorator(FooForm(request.POST))
f.save()
2
  • 1
    Have you tired the approach specified here link Commented Feb 4, 2013 at 22:00
  • could you please post your comment as an answer? :) Commented Feb 4, 2013 at 22:30

2 Answers 2

1

Also try the approach mentioned here https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form

Sign up to request clarification or add additional context in comments.

Comments

0

how can I include fields from the original model which should not be displayed to the user?

Answering this part of your question

class FooForm(ModelForm):
    class Meta:
        model = FooModel
        exclude = ('not_displayed_field',)

1 Comment

This would exclude the field not, hide it != "include fields from the original model". Use widgets = { 'not_displayed_field': forms.HiddenInput() }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.