首页 > 解决方案 > 我的登录表单不起作用,它说在分配之前引用了变量

问题描述

当我转到“/登录”时,出现此错误:

分配前引用的 /login/ 局部变量“表单”处的 UnboundLocalError

这就是它的样子

这是我的看法:

from django import forms
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect

class LoginForm (forms.Form):
    username = forms.CharField()
    password = forms.CharField()

def login (request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
#           username = request.POST['username']
#           password = request.POST['password']
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                login(user)
                return redirect ("/login/success")
        form = LoginForm(request.POST)
    return render (request, 'login.html', {'form':form})

这是模板:

{% include 'base.html' %}

{% load crispy_forms_tags %}

<div class="videos">
<form method="post" class="bootstrap4">
    {% csrf_token %}
    {{ form | crispy }}
    <button type="submit" class="btn btn-success">Submit</button>
</form>
Do't have an acount? Click <a href="/register">here</a> to create an account.
</div>

在分配之前我看不到它在哪里被引用,我偶尔会在 python 中遇到这个错误,而且我永远无法在分配之前弄清楚它在哪里被引用。

标签: pythondjango

解决方案


如果request.method不是POST,则直接转到

return render (request, 'login.html', {'form':form})

并且form没有分配。

当您转到 url 时会发生这种情况,因为方法是GET. 您需要添加else零件。

def login (request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                login(user)
                return redirect ("/login/success")
    else:
        form = LoginForm()

    return render (request, 'login.html', {'form':form})

推荐阅读