Using Your Django Model’s max_length in Your ModelForm

Let’s say you have a field defined as the following in your model:

class User(models.Model):
first_name = models.CharField(max_length=40, null=True)

view raw
models.py
hosted with ❤ by GitHub

You can then use the max_length in your ModelForm like this:

class RegisterForm(forms.ModelForm):
first_name = forms.CharField(max_length=User._meta.get_field('first_name').max_length)

view raw
forms.py
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s