gpt4 book ai didi

python - Django:传输/访问表单完整错误消息

转载 作者:行者123 更新时间:2023-12-01 05:57:17 27 4
gpt4 key购买 nike

在我为学校开发的一个网站上,用户输入他们的学校电子邮件和密码,如果他们已注册,则登录。如果没有,则会显示登录的第二部分,要求输入笔名称并确认密码。正因为如此,以及我复杂的业余 Django 编程,我有一个名为 er 的错误列表。例如,当程序测试电子邮件是否是学校电子邮件时,它可能会添加到错误列表“仅限学校电子邮件”。我也使用两个表单类。页面使用ajax来调用该函数,由于站点较小,因此使用纯html而不是JSON。

在 forms.py 文件中我有:

class log_in(forms.Form):
username = forms.EmailField(error_messages= {'required': "Email Field is required,", 'invalid' : "Invalid Email Address."})
password = forms.CharField(help_text = 'Password Invalid')

class new_user(forms.Form):
username = forms.EmailField(error_messages = {'required': "Email Field is required,", 'invalid' : "Invalid Email Address."})
password = forms.CharField(required=True)
password2 = forms.CharField(required=True)
pen_name = forms.CharField(max_length=30, min_length=3, error_messages = {'required': "Pen Name is required", 'max_length': "Pen Name must be less than 30 characters", 'min_length': "Pen Name must be more than 3 characters"})

问题是我想将 error_message 参数中指定的完整错误消息传输到 er 列表。

这是我的views.py 文件

def user_log_in(request):
er = []
user_pass = log_in(request.POST)
if user_pass.is_valid(): # If it is valid at all
cleaned_info = user_pass.cleaned_data
email_bbn = cleaned_info['username'].split("@")
if 'bbns.org' in email_bbn: # Check if BBN email address
user_object = User.objects.filter(email = cleaned_info['username'])
if user_object.exists():
logged_in_user = auth.authenticate(username=cleaned_info['username'], password=cleaned_info['password'])
#add in is_active
if logged_in_user is not None: #If password is right
if user_object[0].get_profile().activated:
auth.login(request, logged_in_user)
return HttpResponseRedirect("")
else:
return HttpResponse("not_act")
else:
er.append("Incorrect Password")
else: # If new user
new_user_pass = new_user(request.POST)
if new_user_pass.is_valid():
cleaned_info_new = new_user_pass.cleaned_data
if cleaned_info_new['password'] == cleaned_info_new['password2']:
msg = "In order to activate your account at Knights of the Round Table, please click on this link:"
try:
send_mail('Activate', msg, 'michaelrgoldfine@gmail.com', [cleaned_info_new['username']], fail_silently=False)
new_user_object = User.objects.create_user(
username=cleaned_info_new['username'],
password=cleaned_info_new['password'],
email=cleaned_info_new['username']
)
new_user_profile = new_user_object.get_profile()
new_user_profile.pen_name = cleaned_info_new['pen_name']
new_user_profile.activated = False;
new_user_profile.save()
return HttpResponse("not_act")
except:
er.append("Error Sending Email")
else:
er.append('Passwords are not the same')
elif "TN" in request.POST: #If open but not filled in
print "TN"
er.append(new_user_pass.pen_name.error_messages)
else: # if new user field
print "n_usr"
return HttpResponse('n_usr')
else:
er.append("BBN email addresses only")
else:
for e in user_pass.errors:
er.append(e)
errors_template = Template("{% for e in errors %}<li>{{ e }}</li> {% endfor %}")
errors_html = errors_template.render(Context({'errors':er}))
return HttpResponse(errors_html)

我尝试访问错误两次。有一次,在 else 上,您会在末尾看到一个 for 循环,以及在 elif 'TN' 上的两个 else... 最后一个仅返回无效的字段(因此我得到 user_name 或 pen_name)。另一个说该表单没有对象 pen_name 或我用它做的任何事情。

最佳答案

最好在实际表单中添加错误。表单附加有一个 _errors 字典,其中包含表单生成的所有错误。 “非字段错误”(与特定字段不直接相关或与多个字段相关的错误)位于 form._errors['__all__'] 中。所有特定于字段的错误都会进入字段名称的键中。因此,foo 字段的错误将出现在 form._errors['foo'] 中。

现在,_errors 字典中每个项目的错误列表实际上是一个 ErrorList 类型,而不是标准列表。因此,要向表单添加错误,请执行以下操作:

from django.forms.util import ErrorList

form._errors.setdefault('foo', ErrorList()).append('Some error here')

或者,将错误添加到非字段错误:

form._errors.setdefault('__all__', ErrorList()).append('Some error here')

然后,当您的表单呈现时,错误将自然地落在它们应该出现的地方,就像任何正常的验证错误一样。

关于python - Django:传输/访问表单完整错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848612/

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