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

时间:2012-08-07 14:52:57

标签: python django

在我正在为我的学校工作的网站上,用户输入他们的学校电子邮件和密码,如果他们已经注册,他们就会登录。如果没有,则会显示登录的第二部分,要求提供笔命名并确认密码。因为这个,以及我复杂的业余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循环,两个elseelif 'TN'...开始,最后一个只返回无效的字段(所以我得到user_name或pen_name)。另一个说该表单没有对象pen_name或我用它的任何东西。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

现在,_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')

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