验证错误不以Django形式显示

时间:2015-12-31 12:20:39

标签: django django-forms django-views

当我尝试使用已经输入数据库的电子邮件测试我的表单时,它没有像应该的那样给出错误消息,它会重定向回主页。

我的views.py文件如下所示:

from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Lottery
from .models import Lottery_user
from django.core.exceptions import ValidationError

class LotteryForm(forms.ModelForm):
    lottery_type = forms.ModelChoiceField(queryset = Lottery.objects.all(), empty_label=None)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    lottery_numbers = forms.CharField(max_length=12, required=True)
    email = forms.EmailField(required=True)
    telephone = forms.CharField(max_length=18,
                  error_messages={'invalid':'Enter a valid mobile number',
                                  'required':'Enter a valid mobile number'})

    def clean_email(self):
        email = self.cleaned_data['email']
        if Lottery_user.objects.filter(email=email).exists():
             raise ValidationError("Email already exists")
             return email
        if Lottery_user.objects.filter(email=self.cleaned_data['email']).exists():
            raise ValidationError("You've already entered")
            return email

    class Meta:
         model = Lottery_user
         fields = ['lottery_numbers', 'lottery_type', 'first_name', 'last_name', 'email', 'telephone',]

我的表格是:

 <form action="{% url 'lottery_new'  %}" method="post">
        {% csrf_token %}
        <div class="fieldWrapper">
            <label for="lotterytype">Choose a lottery:</label>
            {{ form.lottery_type }}
            <p>See <a href=lottery_instructions>instructions and rules</a></p>
        </div>
        <div class="fieldWrapper">
            <label for="lotterynumbers">Lottery Numbers:</label>
            {{ form.lottery_numbers }}
        </div>
        <div class="fieldWrapper">
            <label for="firstname">First name:</label>
            {{ form.first_name }}
        </div>
        <div class="fieldWrapper">
            <label for="lastname">Last name:</label>
            {{ form.last_name }}
        </div>
        <div class="fieldWrapper">
            {{ form.email.errors }}
            {{ form.email.non_field_errors }}
            <label for="email">Email:</label>
            {{ form.email }}
        </div>
        <div class="fieldWrapper">
            <label for="phonenumber">Telephone Number:</label>
            {{ form.telephone }}
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>

模板表格:

{{1}}

我希望用户无法使用相同的电子邮件输入两次,因此当用户点击使用已使用过的电子邮件地址提交时,该错误应该会出错。

此外,是否有人知道如何在用户提交之前显示错误消息而不是之后?

1 个答案:

答案 0 :(得分:1)

当表单无效时,您应该返回一个新实例化的表单,而应该返回无效表单(带有错误)。尝试:

def lottery_new(request):
   if request.method == 'POST':
       form = LotteryForm(request.POST)
       if form.is_valid():
           ....
       else:
           return render(request, 'lottery/lottery.html' {'form': form})