django一个html先后两个form,在Django中在一个页面上处理多个表单的正确方法

Django基于类的视图提供了一个通用的FormView,但是出于所有意图和目的,它只能处理一个表单。

使用Django的通用视图处理具有相同目标操作URL的多个表单的一种方法是扩展'TemplateView',如下所示; 我经常使用这种方法,我已经把它变成了Eclipse IDE模板。class NegotiationGroupMultifacetedView(TemplateView):

### TemplateResponseMixin

template_name = 'offers/offer_detail.html'

### ContextMixin

def get_context_data(self, **kwargs):

""" Adds extra content to our template """

context = super(NegotiationGroupDetailView, self).get_context_data(**kwargs)

...

context['negotiation_bid_form'] = NegotiationBidForm(

prefix='NegotiationBidForm',

...

# Multiple 'submit' button paths should be handled in form's .save()/clean()

data = self.request.POST if bool(set(['NegotiationBidForm-submit-counter-bid',

'NegotiationBidForm-submit-approve-bid',

'NegotiationBidForm-submit-decline-further-bids']).intersection(

self.request.POST)) else None,

)

context['offer_attachment_form'] = NegotiationAttachmentForm(

prefix='NegotiationAttachment',

...

data = self.request.POST if 'NegotiationAttachment-submit' in self.request.POST else None,

files = self.request.FILES if 'NegotiationAttachment-submit' in self.request.POST else None

)

context['offer_contact_form'] = NegotiationContactForm()

return context    ### NegotiationGroupDetailView

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

context = self.get_context_data(**kwargs)

if context['negotiation_bid_form'].is_valid():

instance = context['negotiation_bid_form'].save()

messages.success(request, 'Your offer bid #{0} has been submitted.'.format(instance.pk))

elif context['offer_attachment_form'].is_valid():

instance = context['offer_attachment_form'].save()

messages.success(request, 'Your offer attachment #{0} has been submitted.'.format(instance.pk))

# advise of any errors

else

messages.error('Error(s) encountered during form processing, please review below and re-submit')

return self.render_to_response(context)

html模板具有以下效果:...

{% csrf_token %}

{{ negotiation_bid_form.as_p }}

...

title="Submit a counter bid"

value="Counter Bid" />

...

{% csrf_token %}

{{ offer_attachment_form.as_p }}

...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值