What happens when I define a field in django forms like this:
class FooForm( ModelForm ):
class Meta:
model = FooModel
fields = ( 'foo', 'bar', ) # I am talking about this field
When I have the fields foo, bar and baz in my models, what happens with baz then in this case?
Are these fields required or not automatically? are they just available? What is actually happening with that field when I am doing this?
When you use fields = ('foo', 'bar',)
, the field baz
does not exist at all in the form, unless you set it explicitly (fields
only "fills in" the missing model fields). When you use form.save()
, baz
is not set to a value on the model either. If the field is required on your model, your code must ensure that it is set before the model is saved to the database.
It is entirely possible, and quite often necessary, to have a required field that's not in the form. E.g. when you have to relate your model to the current user, you can remove the user
field from your form, and use:
obj = form.save(commit=False)
obj.user = request.user
obj.save()
The important distinction here is that form fields are for user input, and model fields are for the data itself.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments