Overriding Django LoginView

Viewed 3842

I am writing a new authentication template to use with my Django apps. I am basing this on a tutorial which I followed.

The tutorial uses the built-in authentication views for password resets which I would like to keep, but I want to customise it slightly. I have an attribute on the user accounts called "disabled" which allows a user to login. On the login view I would like to get it to check to see if the account is disabled, "locked", before allowing the login. For the reset password view I would like to get it to unlock the account if successful.

An example of the path looks like:

from django.contrib.auth import views as auth_views
urlpatterns = [
    path('accounts/login/', auth_views.LoginView.as_view(), name='login')
]

The account model looks like:

class Account(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=150)
    phone = models.CharField(max_length=50, blank=True,null=True)
    date_of_birth = models.DateField(blank=True, null=True)
    picture = models.ImageField(blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    last_login = models.DateTimeField(null=True)
    disabled = models.BooleanField(default=True)
    hash = models.CharField(max_length=128,default=hex(random.getrandbits(128)))

    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name.split()[0]

Do I import this into views and override it there? Is someone able to post a quick example?

1 Answers

You can write your custom view function for login to achieve this:

in views.py

from django.shortcuts import render,redirect
from django.urls import reverse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username,password=password)
        if user:
            if user.is_active:
                login(request,user)
                return redirect(reverse('your_success_url'))
        else:
            messages.error(request,'username or password not correct')
            return redirect(reverse('your_login_url'))
        
                
    else:
        form = AuthenticationForm()
    return render(request,'your_template_name.html',{'form':form})

urls.py

from . import views

urlpatterns = [
    path('accounts/login/', views.login, name='login')
]
Related