Search code examples
djangoregistrationmodelform

Registration form not registering in users


I am doing authentication of users on my website but I have an issue with the form that doesn't take in users. Please help me. Maybe I forgot something. I am not that experienced, Thanks.

Here is the form:

class RegistrationForm(forms.ModelForm):

>     password = forms.CharField(widget=forms.PasswordInput(attrs={
>         'class': 'form-control',
>         'placeholder': 'Enter your password',}))

>     confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={
>         'class': 'form-control',
>         'placeholder': 'Confirm password',}))
>     class Meta:
>         model = Account
>         fields = ('first_name','last_name','phone_number', 'email', 'password')
>     
>     def clean(self):
>         cleaned_data = super(RegistrationForm, self).clean()
>         password = cleaned_data.get('password')
>         confirm_password = cleaned_data.get('confirm_password')
> 
>         if password != confirm_password:
>             raise forms.ValidationError(
>                 'Passwords do not match'
>             )
> 
>     def __init__(self, *args, **kwargs):
>         super (RegistrationForm, self).__init__(*args, **kwargs)
>         self.fields['first_name'].widget.attrs['placeholder'] = 'Enter your first name'
>         self.fields['last_name'].widget.attrs['placeholder'] = 'Enter your last name'
>         self.fields['phone_number'].widget.attrs['placeholder'] = 'Enter your phone number'
>         self.fields['email'].widget.attrs['placeholder'] = 'Enter your email address'
>         for field in self.fields:
>             self.fields[field].widget.attrs['class'] = 'form-control'

model is here

class MyAccountManager(BaseUserManager):
>     def create_user(self, first_name, last_name,username, email, password=None):
>         if not email:
>             raise ValueError('User must have an email address')
>         
>         if not username:
>             raise ValueError('User must have a username')
>         
>         user = self.model(
>             email= self.normalize_email(email),
>             username = username,
>             first_name = first_name,
>             last_name = last_name,
>         )
>         user.set_password(password)
>         user.save(using=self._db)
>         return user
>     def create_superuser(self, first_name, last_name,username, email, password):
>         user =self.create_user( #calling for create user method
>             email=self.normalize_email(email),
>             username=username,
>             password=password,
>             first_name=first_name,
>             last_name=last_name,
>         )
>         user.is_admin = True
>         user.is_active = True
>         user.is_staff = True
>         user.is_superadmin = True
>         user.save(using= self._db)
>         return user 
class Account(AbstractBaseUser):
>     first_name = models.CharField(max_length = 50)
>     last_name  = models.CharField(max_length = 50)
>     username  = models.CharField(max_length = 50, unique=True)
>     email  = models.CharField(max_length = 100, unique =  True)
>     phone_number  = models.CharField(max_length = 50, unique =  True)
> 
>     #required 
>     date_joined = models.DateTimeField(auto_now_add= True)
>     last_login = models.DateTimeField(auto_now_add= True)
>     is_admin = models.BooleanField(default=False)
>     is_staff = models.BooleanField(default=False)
>     is_active = models.BooleanField(default=False)
>     is_superadmin = models.BooleanField(default=False)
>     
>     USERNAME_FIELD = 'email'
>     REQUIRED_FIELDS= ['username', 'first_name', 'last_name']
> 
>     objects = MyAccountManager()
> 
>     def __str__(self):
>         return self.email
> 
>     def has_perm(self, perm, obj=None):
>         return self.is_admin
> 
>     def has_module_perms(self, add_label):
>         return True

then in the template

<div class="card mx-auto" style="max-width:520px; margin-top:40px;">
      <article class="card-body">
        <header class="mb-4"><h4 class="card-title">Sign up</h4></header>
        <form action="{% url 'register' %}">
            {% csrf_token %}

                <div class="form-row">
                    <div class="col form-group">
                        <label>First name</label>
                        {{ form.first_name }}
                    </div> <!-- form-group end.// -->
                    <div class="col form-group">
                        <label>Last name</label>
                        {{ form.last_name }}
                    </div> <!-- form-group end.// -->
                </div> <!-- form-row end.// -->
                <div class="form-row">
                    <div class="form-group col-md-6">
                      <label>Email Address </label>
                      {{ form.email }}
                    </div> <!-- form-group end.// -->
                    <div class="form-group col-md-6">
                      <label>Phone number </label>
                        {{ form.phone_number }}
                    </div> <!-- form-group end.// -->
                </div> <!-- form-row.// -->
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Create password</label>
                        {{ form.password }}
                    </div> <!-- form-group end.// --> 
                    <div class="form-group col-md-6">
                        <label>Repeat password</label>
                        {{ form.confirm_password }}
                    </div> <!-- form-group end.// -->  
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block"> Register  </button>
                </div> <!-- form-group// -->    
                
                {{ form.errors }}
                    
            </form>
        </article><!-- card-body.// -->
    </div> <!-- card .// -->
    <p class="text-center mt-4">Have an account? <a href="">Log In</a></p>
    <br><br>

in the view

    def register(request):
    >     if request.method == 'POST':
    >         form = RegistrationForm(request.POST)

>         if form.is_valid():
>             first_name = form.cleaned_data['first_name']
>             last_name = form.cleaned_data['last_name']
>             phone_number = form.cleaned_data['phone_number']
>             email = form.cleaned_data['email']
>             password = form.cleaned_data['password']
>             username = email.split("@")[0]
> 
>             user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username,
> password=password)
>                                                  
>     
>             user.phone_number = phone_number
>             user.save()
>     else:
>         print("something went wrong")
>         form = RegistrationForm()
> 
>     context = {
>         'form': form,
>     }
>     return render(request, 'accounts/register.html', context)

Solution

  • To whoever with same question in the future, solutions

    1. adding method post
    2. changing to
        ...
            
            user = self.model(
                email= self.normalize_email(email),
                phone_number =phone_number,
                username = username,
                first_name = first_name,
                last_name = last_name,
            )```
    then changing the view to (by removing user.phone_number and user.save
    
    

    def register(request):

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            phone_number = form.cleaned_data['phone_number']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            username = email.split("@")[0]
    
            user = Account.objects.create_user(first_name=first_name, 
             last_name=last_name,
            phone_number = phone_number, email=email, username=username, 
       password=password)
    
    else:
        print("something went wrong")
        form = RegistrationForm()
    
    context = {
        'form': form,
    }
    return render(request, 'accounts/register.html', context)```