用户提交的表单中的数据验证失败后, form.errors 实际上会收集这些错误,因为我一直在调试问题。但是,当我在POST请求后呈现页面时,错误不会在出现错误的字段旁边解析为HTML。
换句话说,import java.util.Scanner;
public class Game {
public static void main(String[] args) throws InterruptedException {
String com = "Computer: ";
System.out.print(com +"H");
Thread.sleep(75);
System.out.print("i");
Thread.sleep(75);
System.out.println(".");
Thread.sleep(2000);
不会在html中呈现。
当用户数据未通过验证时,为了使验证错误在模板中呈现,需要进行哪些更改?
<ul class="errorlist">
# 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 %}
答案 0 :(得分:1)
如果该表单无效,则将其提供给用户。
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})