Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django User model email field: how to make it mandatory

Tags:

django

model

I need to make the email field in the Django User model mandatory. It isn't obvious to me how to do that. Suggestions welcome. I am currently using:

from django.contrib.auth.forms import UserCreationForm

for my User creation form, and combining this with my own custom UserProfileCreateForm

Ian

like image 849
IanSR Avatar asked Mar 30 '11 22:03

IanSR


People also ask

How can we make required field in Django model?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

How do you make a field non mandatory in Django admin?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

How do I make my email address unique in Django?

You have to declare the email field in your AbstractBaseUser model as unique=True .

Is there an email field in Django?

EmailField in Django Forms is a string field, for input of Emails. It is used for taking text inputs from the user. The default widget for this input is EmailInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided.


2 Answers

You should be able subclass the provided registration form and override properties of a field in the Meta class.

from django.contrib.auth.forms import UserCreationForm

# Not sure about the syntax on this one. Can't find the documentation.
class MyUserCreationForm(UserCreationForm):

    class Meta:
        email = {
            'required': True
        }


# This will definitely work
class MyUserCreationForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(MyUserCreationForm, self).__init__(*args, **kwargs)

        self.fields['email'].required = True
like image 63
Derek Reynolds Avatar answered Nov 15 '22 08:11

Derek Reynolds


from django import forms
from django.contrib.auth.models import User


class MyUserForm(forms.ModelForm):

    email = forms.CharField(max_length=75, required=True)

    class Meta:

        model = User
        fields = ('username', 'email', 'password')
like image 26
Dmitry Avatar answered Nov 15 '22 09:11

Dmitry