I have a model form that can't pass validation because I don't want to show some of the fields in the template, they are not important to the user, but are part of the model, and values for them are generated dynamically.How I can set those fields to not be required in the form, (values for them are generated after the POST), so that form can pass validation, and they should be required in the model?
Asked
Active
Viewed 111 times
1 Answers
4
Use a model instance to populate the form with data. Instead of form = Form()
, you get an instance of the model you are going to be saving to -- model_object = Model.objects.get(id=27)
-- (or however you might fetch it), and then use form = Form(instance=model_object)
. This populates the fields with the model data.
If you would rather exclude fields so you can calculate values dynamically, try these steps:
class Form(forms.ModelForm):
class Meta:
model = Model
exclude = ('field_name', 'field_name', 'field_name', ...) # the fields you want to exclude
Then:
def View(request):
if request.POST:
form = Form(request.POST)
if form.is_valid():
model_object = form.save(commit=False) # an unsaved model object
model_object.field = some dynamic value
model_object.another_field = some other dynamic value
model_object.save() # save the model, ignore the form
For more info, you might look at: Setting user_id when saving in view - Django
UPDATE: I added quotes around the 'field_name'
in the exclude line of Form