2
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.
0
With this code, it will determine if the fields are required from your FooModel, depending on the null=True
and blank=True
.
By default, model fields are required, so if they should not be required you have to let django know. Depending on the field type, to make a field not required you need to put null=True
and/or blank=True
.
More information can be found in the docs on how django determines if a field is required or not based on the model.
- [Answered ]-ImportError: No module named threadedcommentsdjango_comments while use django-threadedcomments app
- [Answered ]-Django – schedule recurring task interval
- [Answered ]-Django use Case When to compose sql query
- [Answered ]-ValueError: No JSON object could be decoded – Django request.body
- [Answered ]-How do i include my footer.html in my base.html