1

I am using normal User model in Django to save my users. I would like to add first_name and last_name field, but I don't know how to extend my model and make it work. First and last name should be added in in register form (I use crispy forms).

register view


    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()  # save user to database
            username = form.cleaned_data.get('username')
            messages.success(request, f"User {username} succesfully created! You can login now!")
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

register form

    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)
        self.fields['password1'].label = "Hasło"
        self.fields['password2'].label = "Powtórz hasło"

    email = forms.EmailField()
    name = forms.CharField(
        label="Imię",
        required=True,
        max_length=30,
    )
    surname = forms.CharField(
        label="Nazwisko",
        required=True,
        max_length=30,
    )

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2', 'name', 'surname']
        labels = {
            'username': 'Nazwa użytkownika',
        }
1
  • 1
    Django's User model already has first_name and last_namee. Commented Jan 9, 2021 at 14:21

1 Answer 1

1

Django's User model [Django-doc] already has a first_name and last_name, you can subclass the UserCreationForm and add fields for the first_name and last_name:

from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)
        self.fields['password1'].label = 'Hasło'
        self.fields['password2'].label = 'Powtórz hasło'

    email = forms.EmailField()
    first_name = forms.CharField(
        label='Imię',
        required=True,
        max_length=30,
    )
    last_name = forms.CharField(
        label='Nazwisko',
        required=True,
        max_length=30,
    )

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2', 'first_name', 'last_name']
        labels = {
            'username': 'Nazwa użytkownika',
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.