Django登录authenticate()始终返回None

时间:2019-01-02 13:07:38

标签: python django login

我正在创建一个自定义的django登录视图,但是每当我尝试登录authenticate()时,即使输入正确的密码也始终返回None。 我不想要django的内置登录系统,因为它也不起作用,而且我也无法定义SignInForm。我还尝试在settings.py中定义AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',),但这并没有改变任何内容。

forms.py:

class SignInForm(forms.Form):
username = forms.CharField(error_messages={"required": "Bitte fülle dieses Feld aus.", "invalid": "Dieser Wert ist ungültig."}, min_length=3, max_length=31, required=True, widget=forms.TextInput(attrs={
    "placeholder": "Benutzername oder E-Mail-Adresse", #Username or e-mail
    "id": "username",
    "class": "select selected"
}))

password = forms.CharField(error_messages={"required": "Bitte fülle dieses Feld aus.", "invalid": "Dieses Passwort ist ungültig."}, min_length=8, max_length=1023, required=True, widget=forms.PasswordInput(attrs={
    "placeholder": "Passwort",
    "id": "password"
}))

stayLoggedIn = forms.BooleanField(help_text="Angemeldet bleiben?", required=False, widget=forms.CheckboxInput(attrs={
    "checked": "False",
}))

class Meta:
    model = User
    exclude = ()

field_order = ("username", "password", "stayLoggedIn")

def clean(self):
    cleaned_data = super(SignInForm, self).clean()
    username = cleaned_data.get("username")
    if "@" in username:
        try:
            username = User.objects.get(email__iexact=username).username
        except ObjectDoesNotExist:
            raise forms.ValidationError("Diese E-Mail-Adresse wurde nicht gefunden.")
    else:
        try:
            username = User.objects.get(username=username).username
        except ObjectDoesNotExist:
            raise forms.ValidationError("Dieser Benutzername wurde nicht gefunden.")

    user = authenticate(username=username, password=cleaned_data.get("password"))
    print(user) #Thats always None
    if not user or not user.is_active:
        raise forms.ValidationError("Falsches Passwort.")

    cleaned_data["user"] = user
    return cleaned_data

views.py

def login(request):
if request.method == "POST":
    form = SignInForm(request.POST)
    if form.is_valid():
        cleaned_data = form.clean()
        if cleaned_data.get("user"):
            auth_login(request, cleaned_data.get("user"))
            try:
                request.GET["next"]
            except KeyError:
                return redirect("homepage:homepage")
            return redirect(request.GET["next"])
else:
    form = SignInForm()
return render(request, "authenticate/login.html", {"form": form, "title": "Anmelden"})

0 个答案:

没有答案