FormView未显示验证错误

时间:2017-01-10 13:29:17

标签: django validation django-forms

我的model.py看起来:

class VehicleInquiry(TimeStampedModel):
    inquiry_status = models.PositiveSmallIntegerField(_("inquiry status"), choices=INQUIRY_STATUS_CHOICES, default=1)
    ip = models.GenericIPAddressField(_("IP"), blank=True, null=True)
    full_name = models.CharField(_("full name"), max_length=100)
    address = models.CharField(_("address"), max_length=200)
    phone_code = models.PositiveSmallIntegerField(_("phone code")
    )
    phone = models.CharField(_("phone"), max_length=20)
    email = models.EmailField(_("email"))

is_subscribed = models.BooleanField(_("subscribed"), default=True)
vehicle = models.ForeignKey(VehicleStock, on_delete=models.SET_NULL, blank=True, null=True,
                        related_name="inquiries", verbose_name=_("vehicle")
)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True,
                        related_name="inquiries", verbose_name=_("country")
)
arrival_port = models.ForeignKey(CountryPorts, on_delete=models.SET_NULL, blank=True, null=True,
                        related_name="inquiries", verbose_name=_("arrival port")
)

current_price = models.PositiveIntegerField(_('current price'), null=True, blank=True)
inspection = models.BooleanField(_("pre-export inspection"), default=False)
insurance = models.BooleanField(_("insurance"), default=True)
total = models.PositiveIntegerField(_('total price'), null=True, blank=True)

my form.py:

class VehicleInquiryForm(forms.ModelForm):
    country2 = forms.TypedChoiceField(
        label=_("Country"),
        choices=[('','Arrival Country')]+[(country.id, country.name) for country in Country.objects.all().filter(visible=True).order_by('name')],
        required=True,
    )
    phone_code = ChoiceFieldWithTitles(
        label=_("Country dialing code"),
        choices=[('','Dailing Code', 'Dailing Code')]+[(country.id, '{} (+{})'.format(country.name, country.phone_code), '+{}'.format(country.phone_code)) for country in Country.objects.all().filter(visible=True).order_by('name')],
        required=True,
    )
    arrival_port = forms.TypedChoiceField(
        label=False,
        widget=forms.RadioSelect
    )    

    phone = forms.CharField(
        label=_("Phone"),
        max_length=20,
        required=True,
        validators=[phone_number_validator]
        )

    full_name = StrippedCharField(
        label=_("Full name"),
        max_length=30,
        required=True,
        validators=[full_name_validator]
        )

    address = StrippedCharField(
        label=_("Address"),
        max_length=200,
        required=True
        )        

    class Meta:
        model = VehicleInquiry
        exclude = ('inquiry_status', 'vehicle', 'current_price', 'total')    


    def clean_country2(self):
        country_id = self.cleaned_data['country2']
        try:
            country = Country.objects.get(id=country_id)
        except Country.DoesNotExist:
            raise forms.ValidationError(_('Please select the country'))
        return country_id

    def clean(self):
        cleaned_data = super(VehicleInquiryForm, self).clean()
        dialing_code = cleaned_data['phone_code']
        try:
            dialing_country = Country.objects.get(id=dialing_code)
        except Country.DoesNotExist:
            raise forms.ValidationError(_('Please select the phone code'))
        return self.cleaned_data

    def __init__(self, *args, **kwargs):
        dialing_code = kwargs.pop('phone_code', None)
        super(VehicleInquiryForm, self).__init__(*args, **kwargs)
        self.fields['is_subscribed'].label = _("Keep me updated with news, specials offers and more.")
        self.helper = FormHelper()
        self.helper.template_pack = "bootstrap3"
        self.helper.form_method = "post"
        self.helper.form_id = "vehicle-shipping-form"
        self.helper.form_show_errors = True
        self.initial['insurance'] = True
        self.fields['phone_code'].initial = dialing_code
        self.helper.add_input(
            Submit('inquiry', _('Inquiry'), css_class='btn btn-default',)
        )
        self.helper.form_method = 'post'
        self.helper.layout = Layout(
            Fieldset(
            _("1. Choose Your Final Destination"),
            Div(
                Field('country2', css_class="order-select-country"),
            ),
-- other fields --
)

view.py

class VehicleStockDetailView(FormView):
    template_name = "site/product/vehicle-detail.html"
    template_name_done = "site/contact/contact-us-done.html"
    template_name_done_email = "site/contact/emails/contact-us-done.html"
    form_class = VehicleInquiryForm
    model = VehicleStock

    def get(self, request, slug, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        vehicle = get_object_or_404(VehicleStock, slug=slug)
        similar_vehicles = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
        page_title = vehicle.model

        return render(request, self.template_name, {'page_title': page_title, 'similar_products': similar_vehicles, 'stock_product': vehicle, 'shipping_form': form})

    def post(self, request, slug, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        vehicle = get_object_or_404(VehicleStock, slug=slug)
        similar_vehicles = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
        page_title = vehicle.model
        if form.is_valid():
            form.save()
            return render(self.request, self.template_name_done, {'full_name': request.POST['full_name'], 'email': request.POST['email']})

        return render(self.request, self.template_name, {'page_title': page_title, 'similar_products': similar_vehicles, 'stock_product': vehicle, 'shipping_form': form})

url.py

url(r'^vehicle/(?P<slug>[-_\w]+)/$', VehicleStockDetailView.as_view(), name='vehicle-detail'),

现在,当我填写表单并发送查询时,它没有显示任何错误,但再次显示输入字段值的表单,除了phone_code(它显示默认值)。没有显示错误,但表单未经过验证。我尝试了使用TemplateView和FormView的不同方法。但没有成功。需要任何帮助。

1 个答案:

答案 0 :(得分:0)

您尚未将POSTed数据传递到任何地方的表单。

这是您不应该重写getpost方法的原因之一。各种基于类的视图的关键在于它们几乎为您完成所有这些操作。您应该继承CreateView,以便在表单有效时保存表单,并且您添加的额外逻辑应该在get_context_data中 - 如您所见,这可以避免必须包含相同的代码两次。 / p>

class VehicleStockDetailView(CreateView):
    template_name = "site/product/vehicle-detail.html"
    template_name_done = "site/contact/contact-us-done.html"
    template_name_done_email = "site/contact/emails/contact-us-done.html"
    form_class = VehicleInquiryForm
    model = VehicleStock

    def get_context_data(self, *args, **kwargs):
        context = super(VehicleStockDetailView, self).get_context_data(*args, **kwargs)
        context['vehicle'] = get_object_or_404(VehicleStock, slug=self.kwargs['slug'])
        context['similar_vehicles'] = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
        context['page_title'] = vehicle.model

        return context

    def form_valid(self, form, *args, **kwargs):
        obj = form.save()
        return render(self.request, self.template_name_done, {'full_name': self.request.POST['full_name'], 'email': self.request.POST['email']})

另请注意,您确实不应该在成功时直接呈现模板;你应该总是重定向。同样,表单视图会为您解决此问题。