Search code examples
djangodjango-modelsdjango-formsdjango-authentication

Can the User model be overridden to make the email field required?


For my application, the email field in the Django User model should be required, but by default it's optional.

I searched this question but most answers I found were talking about making the email field required in the customised UserCreationForm for example:

class CustomUserForm(UserCreationForm):
    """Provide a view for creating users with only the requisite fields."""

    class Meta:
        model = User
        # Note that password is taken care of for us by auth's UserCreationForm.
        fields = ('username', 'email')

    def __init__(self, *args, **kwargs):
        super(CustomUserForm, self).__init__(*args, **kwargs)
        self.fields['email'].required = True

but I want to make the email mandatory in the User model as well because I was thinking maybe ModelForm are a frontend thing and the required condition maybe be turned off by the user by using the chrome dev tools, am I wrong? Will making the email required in ModelForm is same as making it required in the user model as well, or can I override the user model to make the email required?


Solution

  • Maybe ModelForm are a frontend thing and the required condition maybe be turned off by the user by using the chrome dev tools, am I wrong?

    You are correct that a user can use tools to make an input item not required, in fact you can often alter the DOM and thus alter the HTML form, or even more simply make use of a tool like curl to make a POST request where you can post arbitrary data.

    But a Form (and by extent an ModelForm) does not only render the form in HTML, it is also used to validate the data. This thus means that if you use a view with:

    def my_view(request):
        if request.method == 'POST':
            form = CustomUserForm(request.POST, request.FILES)
            if form.is_valid():
                # …
            # …
        # …

    then the form.is_valid() will return False if the user did not fill in an email address. A form is thus used to validate, clean data, store data in a model, and render a HTML form.