Search code examples
pythondjangodjango-login

How to block user login with certain status in Django


I'm using Django 1.11 and views based on classes. My user model is customized and it has a status field where it has "enabled, blocked and disabled". I'd like to know how I can only allow users to log in and the others are barred.

Thanks!


Solution

  • you can override default form,

    forms.py

    from django.contrib.auth.forms import AuthenticationForm
    
    class AuthenticationFormWithChekUsersStatus(AuthenticationForm):
        def confirm_login_allowed(self, user):
            if not user.status == 'enabled':
                raise forms.ValidationError(
                    ("Your account has disabled."),
                    code='inactive',
                )
    

    the docs: AuthenticationForm

    And in your urls, it can be like:

    from forms import AuthenticationFormWithChekUsersStatus
    
    url(
        r'^login/$', auth_views.LoginView.as_view(
            authentication_form=AuthenticationFormWithChekUsersStatus
        )
    )
    

    more details: all-authentication-views