验证后,我的表单未显示错误和输入值

时间:2016-12-28 10:15:14

标签: django django-forms django-templates django-crispy-forms

我的model.py

class VehicleInquiry(TimeStampedModel):
    inquiry_status = models.PositiveSmallIntegerField(_("inquiry status"), choices=INQUIRY_STATUS_CHOICES, default=1)
    full_name = models.CharField(_("full name"), max_length=100)
    address = models.CharField(_("address"), max_length=200)
    ---- other fields ----

My Crispy form.py:

class VehicleInquiryForm(forms.ModelForm):
    --- overridden form fields ---    

class Meta:
    model = VehicleInquiry
    fields = ('full_name', 'email')


def __init__(self, request=None, stock_product=None, *args, **kwargs):
    super(VehicleInquiryForm, self).__init__(*args, **kwargs)
    self.fields['is_subscribed'].label = _("Keep me updated")
    self.helper = FormHelper()
    self.helper.template_pack = "bootstrap3"
    self.helper.form_method = "post"
    self.helper.form_id = "vehicle-shipping-form"
    self.initial['insurance'] = True
    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 ---                   
        )

我的CBV view.py:

class VehicleStockDetailView(TemplateView):
    model = StockProduct
    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"

def post(self, request, slug, *args, **kwargs):
    form = VehicleInquiryForm(request.POST)
    ip=""
    if form.is_valid():             
        form.save()
        return render(request, self.template_name_done, {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
        })


    vehicle = get_object_or_404(VehicleStock, slug=slug)
    return render(request, self.template_name, {
        'product': vehicle,
        'form': form
    })

def get(self, request, slug, *args, **kwargs):
    vehicle = get_object_or_404(VehicleStock, slug=slug)
    form = VehicleInquiryForm()
    return render(request, self.template_name, {
        'product': vehicle,
        'form': form
    })

表单正在加载确定为GET,但是当我单击“查询”作为发布请求时,它既不显示错误也不显示输入的值。在我的模板中,我将表单加载为{%crispy form%}。需要帮助。

1 个答案:

答案 0 :(得分:0)

您已更改表单init函数的签名,以便第一个位置参数为request stock_product。你应该避免这样做 - 通常我建议改用kwargs,但在这种情况下你应该完全删除它们,因为你在那个方法中不使用那些值

另请注意,如果使用FormView,您的代码会更简单,它会为您处理几乎所有逻辑。