pythonpython-3.xdjangodjango-modelsdjango-custom-user

Django custom user model with BaseUserManager set is_active=True not working


I'm working on a project using Python(3.7) & Django(3) in which I have implemented a custom user model and inside the User manager, under create_user method I set user.is_active = True but it's not working on signup.

Here's my implementation:

class MyAccountManager(BaseUserManager):
    def create_user(self, email, fullname, password=None):
        if not email:
            raise ValueError('Users must provide the Email.')

        user = self.model(
            email=self.normalize_email(email),
            fullname=fullname,
        )
        user.set_password(password)
        user.is_active = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, fullname, password=None):
        user = self.create_user(
            email=self.normalize_email(email),
            fullname=fullname,
            password=password
        )
        user.is_admin = True
        user.is_staff = True
        user.is_active = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

Here's my signup view:

def registration_view(request):
    if request.method == 'GET':
        return render(request, 'users/register.html')
    if request.method == 'POST':
        form = RegistrationForm(request.POST, request.FILES)
        print('get post req')
        data = {}
        if form.is_valid():
            form.save()
        else:
            print(form.errors)
            return HttpResponse(form.errors)

        return HttpResponseRedirect(reverse_lazy('users:login'))

createsuperuser is working fine, mean it setup is_active = True but when signup as other user types it's not working. What can be wrong?


Solution

  •  def registration_view(request):
        if request.method == 'GET':
            return render(request, 'users/register.html')
        if request.method == 'POST':
            form = RegistrationForm(request.POST, request.FILES)
            print('get post req')
            data = {}
            if form.is_valid():
                user = form.save(commit=False)
                user.is_active = True
                user.save()
      
            else:
                print(form.errors)
                return HttpResponse(form.errors)
    
            return HttpResponseRedirect(reverse_lazy('users:login'))