表单验证不工作Django

时间:2017-09-15 11:54:32

标签: python django django-models django-forms

我不确定我在表单验证方面出错了...我还想显示错误消息,而无法成功提交for。

目前,我正在使用DetailView,其中一个人可以填写BookingForm()

forms.py 来自django.core.validators import RegexValidator

class BookingForm(forms.Form):
    Name = forms.CharField()
    Postcode = forms.CharField(max_length=8,label='Postcode')
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    Phone = forms.CharField(max_length=15,validators=[phone_regex],label='Phone')
    Date = forms.CharField(max_length=30,label='Date')
    Time = forms.CharField(max_length=10,label='Time')

在我的 views.py 中,我定义了def post以允许发布请求。但是,我总是得到ELSE循环返回

def post(self,request,**kwargs):
    # put your own credentials here

    form = BookingForm(self.request.POST)
    if form.is_valid():
        user_phone = form.cleaned_data['Phone']
        postcode = form.cleaned_data['Postcode']
        date = form.cleaned_data['Date']
        account_sid = "***"
        auth_token = "***"
        found = Model.objects.get(id=self.kwargs['pk'])
        client = Client(account_sid, auth_token)
        client.messages.create(
            to=Model.phone_number,
            from_="+442033225719",
            body="You have a new booking." +
                 "Call phone number:{}. Address: {}. Date:{}"
                     .format(user_phone,postcode,date))
        messages.success(request, 'Your booking was reserved.')
    else:
        messages.error(request, 'Error occurred.')
    return redirect('users:detail', pk=self.kwargs['pk'])

我的 model_detail.html 处理表单。

进一步编辑:

我创建了以下HTML模板,我使用{% include 'booking_form.html' %}包含在主模板中:

<!-- Book Now -->
            <form action="" method="post">
                {{ form.non_field_errors }}
                {% csrf_token %}
            <div class="boxed-widget">
                <h3><i class="fa fa-calendar-check-o "></i> Book Now</h3>
                <div class="row with-forms margin-top-0">
                    <div class="col-lg-6 col-md-12">
                        {{ form.name.errors }}
                        <label for="{{ form.name.id_for_label }}">Full Name:</label>
                        {{ form.name }}
                    </div>
                    <div class="col-lg-6 col-md-12">
                          {{ form.postcode.errors }}
                        <label for="{{ form.postcode.id_for_label }}">Postcode:</label>
                        {{ form.postcode }}
                    </div>
                </div>
                <div class="row with-forms  margin-top-0">
                    <div class="col-lg-12 col-md-12">
                        {{ form.name.errors }}
                        <label for="{{ form.name.id_for_label }}">Full Name:</label>
                        {{ form.name }}
                    </div>
                </div>
                <div class="row with-forms  margin-top-0">
                    <div class="col-lg-6 col-md-12">
                        {{ form.date.errors }}
                        <input name="Date" type="text" id="booking-date" data-lang="en" data-large-mode="true" data-min-year="2017" data-max-year="2020">
                    </div>

                    <div class="col-lg-6 col-md-12">
                        {{ form.time.errors }}
                        <input name="Time" type="text" id="booking-time" value="9:00 am">
                    </div>

                </div>

                <!-- progress button animation handled via custom.js -->
                <button type="submit" class="progress-button button fullwidth margin-top-5"><span>Book Now</span></button>
            </div>
            </form>
<!-- Book Now / End -->

forms.py 中的我的BookingForm保持不变。但是,现在,我看不到要输入的字段。我假设这是因为表单没有传递到模板中。

DetailView的 views.py 的完整内容:

class TeacherView(generic.DetailView,FormMixin):
    model = Teacher
    form_class = BookingForm

  def post(self,request,**kwargs):

      form = BookingForm(self.request.POST)
      if form.is_valid():
        user_phone = form.cleaned_data['Phone']
        account_sid = "***"
        auth_token = "***"
        teacher = Teacher.objects.get(id=self.kwargs['pk'])
        client = Client(account_sid, auth_token)
        client.messages.create(
            to=teacher.phone_number,
            from_="+442033225719",
            body=""
        messages.success(request, 'Success Message')
        return redirect('users:index')
    else:
        messages.error(request, 'Error occured.')
        return redirect("users:index")



 def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(TeacherView, self).get_context_data(**kwargs)
    # Add extra context from another model
    context['form'] = self.get_form()
    return context

1 个答案:

答案 0 :(得分:1)

您始终重定向,无论表单是否有效,因此显然您无法显示表单错误。如果您希望在模板中显示表单错误,则需要呈现模板并在验证失败时将其作为响应返回 - 例如使用基于函数的简单视图(如果您坚持使用基于类的通用视图,那么{ {3}}):

def myview(request, ...):
    if request.method == "POST":
        form = MyForm(request.POST):
        if form.is_valid():
            handle_the_form(...)
            messages.success(request, "success message here")
            return redirect(where you want to redirect)
    else:
       # GET, display an empty form
       form = MyForm()
   return render(request, "mytemplate.html", context={"form":form})

同样在您的模板中,您需要使用表单本身而不是硬编码,use a FormMixin with your DetailView

wrt / messages框架的消息也没有显示,这肯定是一个配置问题,所以请重新阅读messages文档并检查您的设置等。