Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new fields in django user model [closed]

How to add new fields in the django user model. The django user model comes with the standard username email and password, however I want users to have more details linked with their account, like let's say phone number or something. What would be the best way to do this?

like image 433
Styxin Avatar asked Feb 02 '19 06:02

Styxin


Video Answer


1 Answers

There is a couple of ways to do that. You can read about all of them in official documentation. Here.

You can either extend User model by creating AbstractUser or create your own model called "Profile" (for example) which is linked to User instance this way:

models.py
class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   phonenumber = models.CharField(verbose_name="phone number", max_lenght=10)
   birthdate = models.DateField(verbose_name="birth date")

then you create forms that person will fill in during registration. It will be User model form and your custom Profile form.

forms.py
class UserForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'first_name', 'email', 'password1', 'password2']


class ProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['birthdate', 'phonenumber']
        widgets = {
            'birthdate': DateInput(attrs={'type': 'date'}),
        }

then you need to save both form's data to User instance when he complete registation.I am using this method:

views.py
def register(request):
    if request.method == "POST":
        u_form = UserForm(request.POST)
        p_form = ProfileForm(request.POST)
        if u_form.is_valid() and p_form.is_valid():
            user = u_form.save()
            p_form = p_form.save(commit=False)
            p_form.user = user
            p_form.save()
            messages.success(request, f'Registration complete! You may log in!')
            return redirect('login')
    else:
        u_form = UserForm(request.POST)
        p_form = ProfileForm(request.POST)
    return render(request, 'users/register.html', {'u_form': u_form, 'p_form': p_form})

So when person goes to registration page he/she sees 2 forms, User form and Profile form and need to fill them to pass registration. When submit button is pressed (post request) view checks if all data is correct and creates User profile with standard fields and custom Profile instance with needed additional fields that is linked to this User and can be accessed (e.g. User.profile.birthdate).

Hope that helps.

like image 73
Lex Izmaylov Avatar answered Oct 09 '22 11:10

Lex Izmaylov