daveoncode
daveoncode

Reputation: 19578

Save a Django ModelForm with default fields values in Model

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()

Upvotes: 0

Views: 5021

Answers (2)

danodonovan
danodonovan

Reputation: 20341

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',)

Upvotes: 0

Related Questions