Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNursultan Bolatbayev
16,774 PointsDont we specify each attribute in Model forms?
I saw another examples, where in ModelForm it is created attribute for each form field. But here it is just included fields. Here what I mean: The video example
class QuizForm(forms.ModelForm):
class Meta:
model = models.Quiz
fields = [
'title',
'description',
'order',
'total_questions',
]
The examples which I saw:
class QuizForm(forms.ModelForm):
title = forms.CharField(max_length=255)
description = forms.TextField()
#so on
class Meta:
model = models.Quiz
Any difference between them? or both are fine?
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsThe answer is Yes, we do specify each field attribute in a ModelForm. The difference is in how this is done. In the form, the field attributes can be defined explicitly as in your second example, or, they can be inferred by referencing which fields should get their attributes from the model
specified in the Meta
section.
In your first example, all of the desired fields are listed in the fields
attribute of the Meta
section. Meta signifies to the form constructor special instructions when building the form. In this case it lists the fields that should get their attributes from the model models.Quiz
Nursultan Bolatbayev
16,774 PointsNursultan Bolatbayev
16,774 PointsThanks for reply. Basically there is no difference between them?
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsThere is a usage difference. To keep the code DRY (don't repeat yourself) the first example is preferred in that you don't specify the field type in the form if it can be discerned from the model definition.
Nursultan Bolatbayev
16,774 PointsNursultan Bolatbayev
16,774 Pointsaa, now I think I get it. If it is ModelForm we can just use fields from Model as first example. But when we create just Form not related to Model (e.g. 'contact us' form), then we do specify each attribute as second example, right?
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsCorrect!