我是Django的新手,我有一个问题。
使用django表单并且无法在循环中获取错误消息。 他们只是没有出现。我不知道为什么会发生这种情况,但我已经改变了形式的产生。简而言之,请看代码
<span id="username" class="input input--madoka">{{ form.username }} {{ form.username.label_tag }}</span>
<span id="first_name" class="input input--madoka">{{ form.first_name }} {{ form.first_name.label_tag }}</span>
<span id="last_name" class="input input--madoka">{{ form.last_name }} {{ form.last_name.label_tag }}</span>
<span id="email" class="input input--madoka">{{ form.email }} {{ form.email.label_tag }}</span>
<span id="password" class="input input--madoka">{{ form.password1 }} {{ form.password1.label_tag }}</span>
<span id="password2" class="input input--madoka">{{ form.password2 }} {{ form.password2.label_tag }}</span>
{% for error in form.errors %}
<h2 style="color: red; font-size: 50px">{{ error }}</h2>
{% endfor %}
查看:
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
messages.success(request, '<p class="success-m animated fadeInUp">You were successfully registered %s </p>'%user.first_name)
return redirect('/')
else:
form = SignupForm()
return render(request, 'signup.html', {'form': form})
不会出现错误消息。
提前致谢。 (对不起,如果我提出错误的问题。)初学者:(
答案 0 :(得分:0)
因为无效表单没有其他条件,所以应该是:
def signup(request):
template_name = 'signup.html'
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
...
else:
# your invalid form after `request.POST` goes here.
# you should render the template again.
print(form.errors)
return render(request, template_name, {'form': form})
else:
form = SignupForm()
return render(request, template_name, {'form': form})