Django - 显示错误的表单错误

时间:2015-10-28 21:41:38

标签: python django forms

当我尝试显示表单错误字段时,我得到了非常奇怪的行为: enter image description here

我已经尝试了几乎所有代码组合,无法理解我做错了什么。如何在表单上显示错误?

我有这样的设置:

base.html文件:

<head>
    ...
</head>
<body>
<header>
    {% if user.is_anonymous %}
        <div class="welcome">
            <span>Welcome!</span>
        </div>
    {% else %}
        <div class="wrapper">
            <a href="/">Home</a>
            <a href="/users/">Public Profiles</a>
            <a href="/users/{{ username }}">My Profile</a>
            <a href="/ribbits">Public Ribbits</a>

            <form action="/logout">
                <input type="submit" id="btnLogOut" value="Log Out">
            </form>
        </div>
    {% endif %}
</header>
<div id="content">
    <div class="wrapper">
        {% block flash %}
            {% if auth_form.non_field_errors or user_form.non_field_errors or ribbit_form.errors %}
                <div class="flash error">
                    {{ auth_form.non_field_errors }}
                    {{ user_form.non_field_errors }}
                    {{ ribbit_form.content.errors }}
                </div>
            {% endif %}
            {% if notice %}
                <div class="flash notice">
                    {{ notice }}
                </div>
            {% endif %}
        {% endblock %}
        {% block content %}
        {% endblock %}
    </div>
</div>
</body>
</html>

register.html:     {%extends&#34; base.html&#34; %}

{% block content %}
    <div class="panel right">
        <h1>New to Ribbit?</h1>
        <p>
        <form action="/signup" method="post">{% csrf_token %}
            {% for field in user_form %}
                {{ field }}
            {% endfor %}
            <input type="submit" value="Create Account">
        </form>
        </p>
    </div>
{% endblock %}

形式:

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Email'}))
    first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'}))
    last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'}))
    username = forms.CharField(widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'}))
    password1 = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password'}))
    password2 = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password Confirmation'}))

    def is_valid(self):
        form = super(UserCreateForm, self).is_valid()
        for f, error in self.errors.iteritems():
            if f != '__all_':
                self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})
        return form

    class Meta:
        fields = ['email', 'username', 'first_name', 'last_name', 'password1',
                  'password2']
        model = User

视图:

def signup(request):
    user_form = UserCreateForm(data=request.POST)
    if request.method == 'POST':
        if user_form.is_valid():
            username = user_form.cleaned_data['username']
            password = user_form.cleaned_data['password2']
            user_form.save()
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
    return register(request, user_form=user_form)


def register(request, user_form=None):
    form = user_form or UserCreateForm()
    return render(request, 'register.html', {'user_form': form})

2 个答案:

答案 0 :(得分:1)

rendering forms manually的Django文档介绍了如何显示错误。

你的行为很奇怪,因为你通过覆盖is_valid()方法做了很奇怪的事情。

它不起作用,因为errorErrorList实例,而不是字符串。当您执行strip_tags(error)时,它不会像您期望的那样剥离标记。

实际上,您正在替换

<ul class="errorlist"><li>This field is required.</li></ul>

进入

<input value="<value goes here>" />

结果是

<input value="<ul class=" errorlist">
<li>This field is required.</li></ul>
" />

浏览器显示时看起来很奇怪。

如果您确实希望将错误显示为表单值,则需要将ErrorList转换为字符串。而不是尝试strip_tags(errors)(注意错误 s ,因为可能有多个),您可以使用

获取错误字符串列表
[error for error in errors]

答案 1 :(得分:0)

register.html <form>标记内<p>。有些人已解释here,这违反了规则。请尝试将<p>放在表单中。

您看到的行为可能是您的浏览器尝试关闭第一个<p>代码。