简体   繁体   中英

Django login not working. Only works for superuser/admin

I was using django-registration-redux for my registration backend earlier and everything worked fine. I then decided to change the registration backend to django's default registration django.contrib.auth and the registration has been working fine but the login doesn't work. However, the thing is, only my superuser acoount can login, every other user can't login, both the regular users and the ones with staff clearance. It keeps giving me invalid username/password error.

Below is the login section of my views.py

def signin(request):
if request.user.is_authenticated:
    return HttpResponseRedirect("/")
form = LoginForm()
errors = None
if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        username = username.lower()
        password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        login(request, user)
        if user.is_staff:
            return redirect('sweet:vendor_index')
        else:
            return redirect('sweet:index')
    else:
        errors = "Invalid Username or Password"
return render(request, 'myregistration/signin.html', {'form':form, 'errors':errors})

Below is my signin.html

{% extends "base.html" %}

{% block title %}sign in{% endblock %}

{% block content %}

<h1>Sign in</h1>

{% if form.errors %}
<p class="error">Please correct the errors below:</p>
  {{ errors }}
{% endif %}

<form method="post" action="{% url 'myregistration:signin' %}">{% csrf_token %}
<dl>
<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.username }}</dd>
<dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.password }}</dd>
<dt><input type="submit" value="sign in" /></dt>
</dl>
</form>
<p>Forgotten password? Click <a href="{% url 'auth_password_reset' %}">here</a> to reset password</p>
{% endblock %}

{% block content-related %}
<p>If you don't have an account, you can <a href="/accounts/register/">sign
up</a> for one.
{% endblock %}

And finally, my urls.py

from django.conf.urls import url
from myregistration import views
from django.contrib.auth import views as auth_views    

app_name = 'myregistration'
urlpatterns = [
    url(r'^register_vendor/', views.register_vendor, name='register_vendor'),
    url(r'^register_customer/', views.register_customer, name='register_customer'),
    url(r'^email_confirm/', views.email_confirm, name='email_confirm'),
    url(r'^password_change/$', views.password_change, name='password_change'),
    url(r'^password_reset/$', auth_views.password_reset, name='password_reset'),
    url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
    url(r'^signin/', views.signin, name='signin'),
    url(r'^logout/', views.logout, name='logout'),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'),
]

Below is my registration method

def register_customer(request):
registered = False

if request.method == 'POST':
    customerform = CustomerSignUpForm(data=request.POST)

    if customerform.is_valid():
        customer = customerform.save(commit=False)
        # Remeber to hash password again
        customer.set_password(customer.password)
        customer.is_active = False
        customer.is_staff = False
        customer.save()

        text_content = "Account Activation Email"
        mail_subject = "Activate your Juggernut account"
        template_name = "myregistration/account_activate.html"
        from_email = customerform.cleaned_data.get('email')
        recipients = [customer.email]
        kwargs = {
            "uidb64":urlsafe_base64_encode(force_bytes(customer.pk)).decode(),
            "token":account_activation_token.make_token(customer)
        }
        activation_url = reverse("myregistration:activate", kwargs=kwargs)
        activation_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), activation_url)

        context = {
            'customer':customer, 
            'activation_url':activation_url
        }
        html_content = render_to_string(template_name, context)
        email=EmailMultiAlternatives(mail_subject, text_content, from_email, recipients)
        email.attach_alternative(html_content, 'text/html')
        email.send()
        return redirect("myregistration:email_confirm")
        registered=True
    else:
        print(customerform.errors)

else:
    customerform = CustomerSignUpForm()
return render(request, 'myregistration/register_customer.html', {'customerform':customerform, 'registered':registered})

As you can see, in your views you have a form class to your view form = LoginForm() , but in your template you're not rendering this form and you won't be able to validate it and the line if form.is_valid(): will always return False.

You have two options, render the form class or change:

form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        username = username.lower()
        password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        login(request, user)
        if user.is_staff:
            return redirect('sweet:vendor_index')
        else:
            return redirect('sweet:index')
    else:
        errors = "Invalid Username or Password"

to:

        username = request.POST.get('username')
        username = username.lower()
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            if user.is_staff:
                return redirect('sweet:vendor_index')
        else:
            return redirect('sweet:index')

Probably the LoginForm class take another parameters and cannot be validated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM