简体   繁体   English

Django 模板不会呈现表单错误

[英]Django template won't render form errors

After a user has submitted a form with data that fails validation, form.errors in fact collects those errors as I've been debugging the issue.在用户提交包含未通过验证的数据的表单后, form.errors实际上会在我调试问题时收集这些错误。 However when I render the page after a POST request, the errors will not be parsed in HTML alongside the fields where errors occur.但是,当我在 POST 请求后呈现页面时,错误将不会在 HTML 中与发生错误的字段一起解析。

In other words <ul class="errorlist"> won't render in the html.换句话说, <ul class="errorlist">不会在 html 中呈现。

What needs to change in order for the validation errors to render in the template when user data doesn't pass validation?当用户数据未通过验证时,需要更改哪些内容才能在模板中呈现验证错误?

# view that renders the template

@login_required(login_url="/accounts/sign_in/")
def new_profile(request, username):
    form = ProfileForm()
    import pdb; pdb.set_trace()
    if request.method == 'POST':
        user_profile = ProfileForm(request.POST)
        if user_profile.is_valid():
            user_profile.cleaned_data.update(user=request.user)
            Profile.objects.create(**user_profile.cleaned_data)
            return HttpResponseRedirect(
                reverse("accounts:profile", kwargs={'username': username})
            )
    return render(request, 'accounts/create_profile.html', {'form': form})
# create_profile.html

{% extends 'layout.html' %}
{% block body %}
    <form action="{% url 'accounts:new_profile' username=user %}" method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>  
{% endblock %}
-> if request.method == 'POST':
(Pdb) n
-> user_profile = ProfileForm(request.POST)
(Pdb) n
-> if user_profile.is_valid():
(Pdb) p user_profile.errors
{'birth': ['Enter a valid date.'], 'bio': ['Add more detail to your bio.']}
(Pdb) p user_profile.as_p()
# As shown when calling .as_p() in the console
<ul class="errorlist">
    <li>Enter a valid date.</li>
</ul>
<p>
<label for="id_birth">Birth:</label> 
<input id="id_birth" name="birth" placeholder="None" type="text" value="12-23" />
</p>
<ul class="errorlist">
    <li>Add more detail to your bio.</li>
</ul>
<p><label for="id_bio">Bio:</label> 
<input id="id_bio" name="bio" placeholder="None" type="text" value="Comments" />
</p>
<p><label for="id_avatar">Avatar:</label> <input id="id_avatar" name="avatar" placeholder="None" type="file" /></p>

Supply the form back to the user if it is not valid..如果表单无效,请将表单返回给用户。

else:
    form = ProfileForm()

@login_required(login_url="/accounts/sign_in/")
def new_profile(request, username):
    import pdb; pdb.set_trace()
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.cleaned_data.update(user=request.user)
            Profile.objects.create(**form.cleaned_data)
            return HttpResponseRedirect(
                reverse("accounts:profile", kwargs={'username': username})
            )
    else:
        form = ProfileForm()
    return render(request, 'accounts/create_profile.html', {'form': form})

In your template you can use {{form.errors}} to display the errors在您的模板中,您可以使用{{form.errors}}来显示错误

{% extends 'layout.html' %}
{% block body %}
{% if form.errors %}
   {{form.errors}}
{% endif %}
    <form action="{% url 'accounts:new_profile' username=user %}" method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>  
{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM