1

在我正在为我的学校工作的网站上,用户输入他们的学校电子邮件和密码,如果他们已经注册,他们就会登录。如果没有,登录的第二部分会显示,要求输入笔名并确认密码。正因为如此,以及我复杂的业余 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 列表。

这是我的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 循环,然后else从那个开始两个 selif 'TN'...最后一个只返回无效的字段(所以我得到 user_name 或 pen_name)。另一个说表单没有对象 pen_name 或我使用它的任何东西。

4

2 回答 2

1

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

于 2012-08-07T15:30:06.663 回答
1

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

现在,dict 中每个项目的错误列表_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')

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

于 2012-08-07T16:37:30.197 回答