Model field and form field relationship

Hello. If I had a model like so:

class Article(models.Model):
    headline = models.CharField(
        max_length=200,
        null=True,
        blank=True,
        help_text='Use puns liberally',
    )
    content = models.TextField()

And a modelform like so:

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['headline', 'content']

How would I apply all of the attributes on the model field, on my form field. E.g if the headline field in the form is over 200 characters, and max_length=200 is specified on the headline model field, would a ValidationError be raised automatically?

Or would I have to override the headline field itself in the form like below to ensure a ValidationError gets raised? Thanks.

class ArticleForm(ModelForm):
    headline = forms.CharField(
        max_length=200,
        required=False,
        help_text='Use puns liberally',
    )

    class Meta:
        model = Article
        fields = ['headline', 'content']

What you’re looking for is the documentation on Creating Forms from Models, particularly the field types section for CharField.

Ken

1 Like

Hello. So for example, the docs state:

A CharField as a model field is equivalent to the following in the form:

CharField with max_length set to the model field’s max_length and empty_value set to None if null=True .

So when writing the modelform, I wouldn’t have to add any more code than the ArticleForm shown above? Or would I have to rewrite the field in the modelform and explicitly set the same attributes that the model has; e.g setting a max_length on a field in the form, when the corresponding model field has a max_length attached already.

What the docs are telling you is that when you’re letting the ModelForm create a CharField, it will create that field using the max_length of the model field. So no, you would not need to add anything else. (Your first samples)

However, if you define the field in your form (second sample), then you would also need to specify the max_length if you want it to apply.

Great thanks, this helps a lot.