Django:POST和GET的不同视图 - 表单验证错误

时间:2018-01-09 18:39:30

标签: python django django-forms django-views django-urls

我有DemandDetailView(DetailView)BidCreationView(CreateView)

DemandDetailView页面上,有一个表单(用于创建出价),可将数据发布到BidCreationView

如果form无效,我无法弄清楚要做什么。我想再次使用DemandDetailView呈现form errors并保留相应的网址。

class DemandDetailView(DetailView):
    model = Demand
    template_name = 'demands/detail.html'


    def dispatch(self, request, *args, **kwargs):
        self.bid_creation_form = BidCreationForm(request.POST or None, request.FILES or None,request=request)
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bid_creation_form']=self.bid_creation_form
        return context

class BidCreationView(CreateView):
    http_method_names = ['post']
    model = Bid
    form_class = BidCreationForm

    def get_success_url(self):
        return reverse_lazy("demands:demands")

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update({'request': self.request})
        return kwargs

    def form_valid(self, form):
        form.instance.demand_id = self.kwargs.pop('demand_id')
        return super().form_valid(form)

你有什么想法吗?我唯一的想法是使用不太可能是最佳方式的会话。

1 个答案:

答案 0 :(得分:0)

您可以使用表单对象中的is_valid()方法。类似的东西:

class DemandDetailView(DetailView):
    model = Demand
    template_name = 'demands/detail.html'


def dispatch(self, request, *args, **kwargs):
    form = BidCreationForm(request.POST or None, request.FILES or None,request=request)
    if form.is_valid():
         self.bid_creation_form = form
    return super().dispatch(request, *args, **kwargs)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['bid_creation_form']=self.bid_creation_form
    return context

选项#2(个人选择):

forms.py

from django import forms
from .models import Bid

class BidCreationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(BidCreationForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs = {"class": "form-control"}

    class Meta:
        model = Bid
        fields = ('user', 'demands', 'amount', 'transaction')

查看表单中的Meta类。它明确地调用Bid Model和fields属性是指Model Model中的Bid字段。现在您可以在任何视图中调用此表单而无需调用另一个视图。如果你想为这个表单添加逻辑,比如计算总金额或类似的东西,那么也应该在表单中进行。编写一次代码,不要重复自己。