0

I have been learning about how forms, and now ModelForms, work.

In a video by Max Goodridge, he redefines a field for one of his ModelFields in his ModelForm class. That is, he manually adds a field to his ModelForm class that could have been auto-generated by the ModelForm framework. From what I have read and understood thus far, that may be something to avoid. Though, that is not where my question lies.

I am wondering how redefining fields within a ModelForm class works. In the Django Docs, it is stated (with an example) that a ModelForm instance will have a form field for every model field specified. What happens then, when a form field is explicitly defined in a ModelForm instance? Are two fields generated or does ModelForm recognise that a field is already defined, thus not generating another one?

Furthermore, what exactly does adding an attribute to a ModelForm instance in the views do? For example, I have seen this:

form = ExampleForm(request.POST)
if form.is_valid():
    post = form.save(commit=False)
    post.user = request.user    # herein lies my confusion
    post.save()

What exactly is happening here? I have seen people do this and adding a timestamp as well, but I fail to understand exactly what it does. Presumably, the .save() method recognizes the attribute name 'user' and adds it to the database if the name corresponds with a Model-field name 'user'?

  1. What happens when a form field is explicitly defined in a ModelForm instance?

  2. How does adding an attribute with information for a model-field in a ModelForm instance work?

Thank you!

1 Answer 1

1

When you define a field at class level, the form will use that definition rather than create one from the model field. Far from being something to avoid, this is the correct thing to do if you want to completely customise a field.

Your second question is hard to understand. Save is not "recognising" anything. form.save() returns the instance of the model, on which you can set any field values as normal.

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

4 Comments

Thank you! By the .save() method I mean the one used with commit=True, ultimately saving the form (form.save())
I still don't understand - you don't have any code with commit=True.
Well I'm still not sure where your confusion is. post is the model instance, not the form. Once again, there is no special recognising going on.
Alright! So the .save() method gets a hold of the validated request.POST information and saves it to the database? How does it obtain the data passed to the ModelForm? Through 'cleaned_data'?

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.