Python Django模板赢得';不渲染表单错误
在用户提交了一个包含未通过验证的数据的表单后,form.errors实际上会在我调试问题时收集这些错误。但是,当我在POST请求后呈现页面时,错误将不会与出现错误的字段一起在HTML中解析 换句话说,Python Django模板赢得';不渲染表单错误,python,django,Python,Django,在用户提交了一个包含未通过验证的数据的表单后,form.errors实际上会在我调试问题时收集这些错误。但是,当我在POST请求后呈现页面时,错误将不会与出现错误的字段一起在HTML中解析 换句话说,不会在html中呈现 当用户数据未通过验证时,需要进行哪些更改才能在模板中呈现验证错误 # view that renders the template @login_required(login_url="/accounts/sign_in/") def new_profile(request,
不会在html中呈现
当用户数据未通过验证时,需要进行哪些更改才能在模板中呈现验证错误
# 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})
#创建_profile.html
{%extends'layout.html%}
{%block body%}
{%csrf_令牌%}
{{form}}
提交
{%endblock%}
->if request.method==“POST”:
(Pdb)n
->user\u profile=ProfileForm(request.POST)
(Pdb)n
->如果用户\u profile.is\u有效():
(Pdb)p用户配置文件错误
{'birth':['输入有效日期'],'bio':['向您的bio添加更多详细信息。]}
(Pdb)p用户配置文件
#如在控制台中调用.As_p()时所示
- 输入有效日期
出生:
- 为你的简历添加更多细节
生物:
化身:
如果表单无效,请将表单提供给用户
else:
form = ProfileForm()
我不是在第一行视图中这样做的吗?我尝试了你的建议,但还是遇到了问题。
-> 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>
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})