Question

When login is attempted with admin credentials it is working and redirecting to admin interface but it is not showing the admin interface, it is showing the admin login page. How should I redirect admin user directly to the admin interface ?

views.py

class LoginView(TemplateView, FormMixin):

"""
Login page
"""
template_name = 'signin.html'
form_class = LoginForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'signin.html'
success_url = '/frontend/'

def form_valid(self, form):
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active and user.is_superuser:
            return HttpResponseRedirect('/admin/')
        elif user.is_active:
            login(self.request, user)
            return HttpResponseRedirect(self.get_success_url())
        else:
            return HttpResponseRedirect(reverse('login'))
    else:
            return HttpResponseRedirect(reverse('login'))

def form_invalid(self):
    return HttpResponseRedirect(reverse('login'))

def get_success_url(self):
    if self.success_url:
        redirect_to = self.success_url
    else:
        redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

    netloc = urlparse.urlparse(redirect_to)[1]
    if not redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
    elif netloc and netloc != self.request.get_host():
        redirect_to =  settings.LOGIN_REDIRECT_URL

    return redirect_to

def post(self, request, *args, **kwargs):
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid()
Was it helpful?

Solution

As per understanding with your code .
You are doing wrong at

if user.is_active and user.is_superuser:
   return HttpResponseRedirect('/admin/')
elif user.is_active:
   login(self.request, user)

when you are trying to login code always go to if statement that's why it is redirecting to /admin/ but not making login actually.
Your code should be like

if user.is_active and user.is_superuser:
   login(self.request, user)         # you must put login here and it will work fine
   return HttpResponseRedirect('/admin/')
elif user.is_active:
   login(self.request, user)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top