8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

在Django中处理一个页面上的多个表单的正确方法

picobit 2月前

192 0

我有一个模板页面需要两个表单。如果我只使用一个表单,那么一切正常,如以下典型示例所示:if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_va...

我有一个模板页面需要两个表单。如果我只使用一个表单,那么一切就都正常了,如以下典型示例所示:

if request.method == 'POST':
    form = AuthorForm(request.POST,)
    if form.is_valid():
        form.save()
        # do something.
else:
    form = AuthorForm()

但是,如果我想使用多个表单,我该如何让视图知道我只提交其中一个表单而不是另一个表单(即它仍然是 request.POST 但我只想处理发生提交的表单)?


这是 基于答案的解决方案,其中 expectedphrase bannedphrase 是不同表单的提交按钮的名称,而 expectedphraseform bannedphraseform 是表单。

if request.method == 'POST':
    if 'bannedphrase' in request.POST:
        bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
        if bannedphraseform.is_valid():
            bannedphraseform.save()
        expectedphraseform = ExpectedPhraseForm(prefix='expected')
    elif 'expectedphrase' in request.POST:
        expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
        if expectedphraseform.is_valid():
            expectedphraseform.save() 
        bannedphraseform = BannedPhraseForm(prefix='banned')
else:
    bannedphraseform = BannedPhraseForm(prefix='banned')
    expectedphraseform = ExpectedPhraseForm(prefix='expected')
帖子版权声明 1、本帖标题:在Django中处理一个页面上的多个表单的正确方法
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由picobit在本站《forms》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 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模板效果如下:

    ...
    
    <form id='offer_negotiation_form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
        {% csrf_token %}
        {{ negotiation_bid_form.as_p }}
        ...
        <input type="submit" name="{{ negotiation_bid_form.prefix }}-submit-counter-bid" 
        title="Submit a counter bid"
        value="Counter Bid" />
    </form>
    
    ...
    
    <form id='offer-attachment-form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
        {% csrf_token %}
        {{ offer_attachment_form.as_p }}
    
        <input name="{{ offer_attachment_form.prefix }}-submit" type="submit" value="Submit" />
    </form>
    
    ...
    
返回
作者最近主题: