user13729875
user13729875

Reputation:

How can i add first name and last name in my registration form

i'm working with Django and i customized the Auth System to have an email registration instead of the username,

i would like to add the first name and the last name input in my form registration.

This is my code

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    username = models.CharField(max_length=255, unique=False, blank=True, null=True)
    email = models.EmailField('email address', unique=True)
    USERNAME_FIELD = 'email'   
    REQUIRED_FIELDS = ['username'] 

Already i did

<form method="post">
{% csrf_token %}
<input type="text" name="first_name">
<input type="text" name="last_name">
{{form.as_p}}
<input type="submit">
</form>

as you can see i added two html field in my form but it doesn't work, both of the columns (first_name + last_name ) still empty in my database table

Upvotes: 0

Views: 2824

Answers (1)

Daniel Diaz
Daniel Diaz

Reputation: 454

The class AbstractUser has already defined first_name and last_name attributes source code, so it would be redundant to rename those fields unless you add other parameters.

Step1: Create a custom signup form that extends UserCreationForm

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):

    class Meta:
        model = get_user_model()
        fields = ("first_name", "last_name",
                  "email", "username", "password1", "password2")

step2: Create a view that uses the custom form

from django.views import generic
from .forms import SignUpForm

class SignUpView(generic.CreateView):
    """
    Allows the User to Create a New Account
    """
    form_class = SignUpForm
    template_name = "AUTHENTTICATION_APP/singup.html"
    success_url = reverse_lazy('some:reversed_url')

step3: Create a URL to signup users:

from .views import SignUpView

urlpatterns = [
    path("signup/", SignUpView.as_view(), name="signup"),
]

Now if you try:

<form method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit">
</form>

It should work, if it doesn't try to write down each field.

{{form.first_name}}
{{form.last_name}}

Upvotes: 4

Related Questions