我是 Django 新手。
我的登录页面只需要“用户名”和“密码”,如果它们留空或填写不正确,我想提出 ValidationError。我创建了代码,但它只是引发了
“/login/ 处的 KeyError”和“/login/ 处的 UnboundLocalError:分配前引用的局部变量 'context'”
如何修复我的代码?
视图.py
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password = form.cleaned_data['password']
uasite1= authenticate(username=username, password=password)
if uasite1 is not None:
login(request, uasite1)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('login.html', context, context_instance=RequestContext(request))
else:
form = LoginForm()
context ={ 'form' : form}
return render_to_response('login.html',{'form': form}, context_instance=RequestContext(request))
表格.py
class LoginForm(forms.Form):
username = forms.CharField(label = (u'User Name'))
password = forms.CharField(label = (u'Password'),widget = forms.PasswordInput(render_value=False))
def clean_username(self):
data = self.cleaned_data['username']
if not data:
raise forms.ValidationError("Please Enter Username.")
return data
def clean_password(self):
data = self.cleaned_data['password']
if not data:
raise forms.ValidationError("Please Enter Password.")
return data
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
try:
User.objects.get(username=username, password=password)
except User.DoesNotExist:
raise forms.ValidationError("Email or Password is incorrect.")
return self.cleaned_data