Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django:传输/访问表单完整错误消息_Python_Django - Fatal编程技术网

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

Python Django:传输/访问表单完整错误消息,python,django,Python,Django,在我为我的学校工作的网站上,用户输入他们的学校电子邮件和密码,如果他们已经注册,他们就会登录。如果没有,则会显示登录的第二部分,要求输入笔名并确认密码。由于这个原因,以及我复杂的业余Django编程,我有一个名为er的错误列表。例如,当程序测试电子邮件是否为学校电子邮件时,可能会将其添加到er列表中“仅限学校电子邮件”。我还使用了两个表单类。页面使用ajax来调用此函数,由于站点规模较小,它使用纯html而不是JSON 在forms.py文件中,我有: class log_in(forms.Fo

在我为我的学校工作的网站上,用户输入他们的学校电子邮件和密码,如果他们已经注册,他们就会登录。如果没有,则会显示登录的第二部分,要求输入笔名并确认密码。由于这个原因,以及我复杂的业余Django编程,我有一个名为er的错误列表。例如,当程序测试电子邮件是否为学校电子邮件时,可能会将其添加到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列表

这是my 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)
def用户登录(请求):
er=[]
用户通过=登录(request.POST)
如果用户_pass.is _valid():#如果它是有效的
已清理的\信息=用户\通行证。已清理的\数据
电子邮件\u bbn=已清理的\u信息['username']。拆分(“@”)
如果电子邮件中有“bbns.org:#请检查bbn电子邮件地址
user\u object=user.objects.filter(email=cleaned\u info['username'])
如果用户_对象存在():
登录用户=auth.authenticate(用户名=cleaned\u info['username'],密码=cleaned\u info['password'])
#加载项处于活动状态
如果登录用户不是无:#如果密码正确
如果用户\u对象[0],则获取\u配置文件()。已激活:
身份验证登录(请求、登录用户)
返回HttpResponseRedirect(“”)
其他:
返回HttpResponse(“非行动”)
其他:
附加(“不正确的密码”)
其他:#如果是新用户
new\u user\u pass=新用户(request.POST)
如果新的\u用户\u通过。是否有效()
已清理的\u信息\u新=新的\u用户\u通行证。已清理的\u数据
如果已清理信息新['password']==已清理信息新['password2']:
msg=“要激活您在圆桌骑士的帐户,请单击此链接:”
尝试:
发送邮件('Activate',msg,'michaelrgoldfine@gmail.com“,[cleaned_info_new['username']],fail_静默=False)
新建用户\u对象=user.objects.create\u用户(
用户名=已清理的\u信息\u新['username'],
password=已清理的\u info\u new['password'],
电子邮件=已清理信息\u新['username']
)
新建用户配置文件=新建用户对象。获取配置文件()
新建\用户\配置文件.pen \名称=已清理\信息\新建['pen \名称']
new_user_profile.activated=False;
新建用户配置文件。保存()
返回HttpResponse(“非行动”)
除:
附加(“发送电子邮件时出错”)
其他:
er.append('密码不相同')
request.POST中的elif“TN:#如果打开但未填写
打印“TN”
追加(新用户密码、笔名、错误消息)
else:#如果是新用户字段
打印“n_usr”
返回HttpResponse('n_usr')
其他:
er.追加(“仅BBN电子邮件地址”)
其他:
对于e in user_pass.errors:
er.追加(e)
errors\u template=template(“{%for e in errors%}
  • {{e}
  • {%endfor%}”) errors\u html=errors\u template.render(上下文({'errors':er})) 返回HttpResponse(错误\u html)

    我试着接受错误两次。有一次,在
    else
    上,您看到右端有一个for循环,还有两个
    else
    s在
    elif'TN'…
    上,最后一个只返回无效的字段(因此我得到用户名或笔名)。另一个表示表单没有对象笔名或我使用它的任何用途。

    该数组可能看起来像错误[I]。字段[I]。错误,因此您只调用字段名,而不是错误消息。在Template()函数中调用e.error。

    最好在实际表单中添加错误。表单附带了一个
    \u errors
    dict,其中包含表单生成的所有错误。“非字段错误”(与特定字段无关或与多个字段相关的错误)以
    形式出现。所有特定于字段的错误都会进入字段名称的键中。因此,
    foo
    字段的错误将以
    形式出现

    现在,
    \u errors
    dict中每个项目的错误列表实际上是
    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')
    

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

    那么问题是什么?