Search code examples
djangodjango-formsdjango-authentication

Create User in Django through form


I want to have a user sign up form in Django, I know that for the Backend I should have something like this:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')


>>> user.last_name = 'Lennon'
>>> user.save()

However, I don't know how to make the Frontend. I've already looked up in the Django documentation and found the UserCreationForm class and it says it's deprecated. What should I do? Thank you


Solution

  • Try something like this:

    #forms.py
    
    class UserCreationForm(forms.ModelForm):
        """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    
    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')
    
    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("Passwords don't match")
        return password2
    
    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
    

    You should read this section of the Django Docs on authentication.