Django Model Forms - Setting a required field
In Django 3.0 if you for example want to make email required in user registration form, you can set required=True
:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyForm(UserCreationForm):
email = forms.EmailField(required=True) # <- set here
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
You can modify the fields in __init__
in the form. This is DRY since the label, queryset and everything else will be used from the model. This can also be useful for overriding other things (e.g. limiting querysets/choices, adding a help text, changing a label, ...).
class ProfileEditPersonalForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['country'].required = True
class Meta:
model = Profile
fields = (...)
Here is a blog post that describes the same "technique": http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/