gpt4 book ai didi

python - forms.py 的问题

转载 作者:行者123 更新时间:2023-11-28 17:49:50 25 4
gpt4 key购买 nike

当我提交表单时,我在 forms.py 的第 25 行 password1=self.cleaned_data['password1'] 的 password1 处收到 KeyError。文件代码如下:

forms.py的代码是:

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker

class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))

class Meta:
model=Drinker
exclude=('user',)

def clean_username(self):
username=self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("The Username is already taken, please try another.")
def clean_password(self):
password=self.cleaned_data['password']
password1=self.cleaned_data['password1']
if password != password1:
raise forms.ValidationError("The Password did not match, please try again.")
return password

html文件的代码是:

{% extends "base.html" %}
{% block extrahead %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>
<script>
$(function() {
$( "#id_birthday" ).datepicker();
});
</script>
{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p>Please correct the following fields:</p>{% endif %}
<div class="register_div">
{% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
<p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label></p>
<p>{{ form.username }}</p>
</div>
<div class="register_div">
{% if form.email.errors %}<p class="error">{{ form.email.errors }}</p>{% endif %}
<p><label for="email"{% if form.email.errors %} class="error"{% endif %}>Email:</label></p>
<p>{{ form.email }}</p>
</div>
<div class="register_div">
{% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
<p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label></p>
<p>{{ form.password }}</p>
</div>
<div class="register_div">
{% if form.password1.errors %}<p class="error">{{ form.password1.errors }}</p>{% endif %}
<p><label for="password1"{% if form.password1.errors %} class="error"{% endif %}>Password1:</label></p>
<p>{{ form.password1 }}</p>
</div>
<div class="register_div">
{% if form.birthday.errors %}<p class="error">{{ form.birthday.errors }}</p>{% endif %}
<p><label for="birthday"{% if form.birthday.errors %} class="error"{% endif %}>Birthday:</label></p>
<p>{{ form.birthday }}</p>
</div>
<div class="register_div">
{% if form.name.errors %}<p class="error">{{ form.name.errors }}</p>{% endif %}
<p><label for="name"{% if form.name.errors %} class="error"{% endif %}>Name:</label></p>
<p>{{ form.username }}</p>
</div>
<p><input type="submit" value="submit"/></p>
</form>
{% endblock %}

查看文件是

from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from drinker.models import Drinker
from django.template import RequestContext
from drinker.forms import RegistrationForm

def DrinkerRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
#return render_to_response('register')
form = RegistrationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password = form.cleaned_data['password'])

user.save()
# drinker=user.get_profile()
# drinker.name=form.cleaned_data['name']
# drinker.birthday=form.cleaned_data['birthday']
# drinker.save()
drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
drinker.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html',{'form':form} , context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them a blank registration form '''

form = RegistrationForm()
context={'form':form}
return render_to_response('register.html',context , context_instance=RequestContext(request))

最佳答案

Django 为表单中的每个字段调用 clean_xxx() 方法。当字段有效时,它会将键/值添加到 cleaned_data。当 Django 调用 clean_password 并且尚未处理字段 password1 时,cleaned_data 将不包含 password1 的键/值对。那是您当前遇到的错误。

要修复它,您需要将密码验证移至 clean(),它会在 Django 单独检查每个字段后调用。此方法可用于执行涉及表单的多个字段(即整个表单)的验证。

这也是有道理的,因为您要引发的错误是关于 passwordpassword1 之间的不匹配,而不仅仅是字段 password (您当前正在清理的区域)。

关于python - forms.py 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12197058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com