2017-08-23 88 views
0

我是新的Django,我有一個問題。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

好吧,我會添加我的視圖代碼 –

+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})