将两种形式的脆皮形式上下文名称定义为一个 [英] Define crispy forms context names for two forms in one

查看:124
本文介绍了将两种形式的脆皮形式上下文名称定义为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用django创建一个脆弱的表单,它的顶部有一个持久化表单,但是在同一页面底部有一个变量表单,这取决于下拉菜单中的选择。



脆皮形式的文件表明,在执行以下操作时可以这样做:

 < form action ={%url submit_survey%}class =uniFormmethod =post> 
{%crispy first_form%}
{%crispy second_form%}
< / form>

但是,这显然取决于表单的上下文名称,但我找不到任何资源这解释了如何真正设置我想要显示的表单的上下文变量。



下面是顶部表单和一个可能的底部表单的示例:

  from django import forms 
$ b $ from crispy_forms.helper import FormHelper $ b $ from crispy_forms.layout import Layout, ButtonHolder,提交

类BusinessForm(forms.ModelForm):

group_id = forms.ModelChoiceField(GroupModel.objects.all())

def __init __(self,* args,** kwargs):
super(BusinessForm,self).__ init __(* args,** kwargs)

self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.layout =布局(
'group_id',$ b $'contact_name',
'business_name',
'地址栏1',
'address_line_2',
'邮编',
'电话',
'电子邮件',
'网页',
ButtonHolder(
Submit('submit','Add business',css_class ='btn-primary')



class Meta:
model = BusinessModel
字段=(
'group_id',
'contact_name',
'business_name',
'address_line_1',
'address_line_2',
'邮编',
'电话',
'电子邮件',
'网络',


类AttractionExtrasForm(forms.ModelForm):

classification_id = forms.ModelChoiceField(AttractionClassModel.objects.all())

def __init __(self,* args,** kwagrs):
super(AttractionExtrasForm,self) .__ init __(* args,** kwargs)

self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.layout = Layout($ b $'classification_id',


class Meta:
model = AttractionExtrasModel
fields =(
'classification_id',

和视图:

  class BusinessView(
views.LoginRequiredMixin,
views.FormValidMessageMixin,
generic.edit.CreateView
):

form_class = BusinessForm
model = BusinessModel
template_name =business / business.html
success_url = reverse_lazy('business:add_business')
from_valid_message =您已成功创建了一个业务。
$ b $ def form_valid(self,form):
return super(BusinessView,self).form_valid(form)

模板:

  {%extends'_layouts / base.html'% } 

{%load crispy_forms_tags%}

{%block title%}
新增业务| {{block.super}}
{%endblock title%}

{%block headline%}
< h1>添加商户< / h1>
{%endblock headline%}

{%block content%}
{%crispy form%}
< / form>
{%endblock content%}

这将显示正常形式,因为它只是调用



干杯


有人知道如何做到这一点吗?
$ b

      ... 

def get_context_data(self,** kwargs):
context = super(BusinessView,self).get_context_data(** kwargs)
context ['form_2'] = AttractionExtrasForm(instance = self.model())#if createview
#context ['form_2'] = AttractionExtrasForm(instance = self.object)#if updateview

返回上下文

而且您必须分别验证

 如果form.is_valid()和form_2.is_valid():
返回self.form_valid(form,form_2)
else :
return self.form_invalid(form,form_2)

如果你模型已连接(一个FK字段与另一个)

  def form_valid(self,form,form_2):
if不是self.object:#createview
self.object = form.save()
else:#updateview
form.save()

form_2.instance = self .object
form_2.save()

return HttpResponseRedirect(self.get_success_url())

def form_invalid(self,form,form_2):
返回self.render_to_response(
self.get_context_data(
form = form,
form_2 = form_2


如果您希望 form_2 的许多实例可以使用inlineformset_factory https://docs.djangoproject.com/en/dev/topics/forms/modelforms /#django.forms.models.BaseInlineFormSet



模板

 < form method =post> {%csrf_token%} 
{%crispy form%}
{%crispy form_2% }
< / form>


I'm trying to create a crispy form with django that has a persistent form at the top, but then a variable form at the bottom of the same page, which is dependent on the choice out of a drop-down menu.

The crispy forms documentation says that this is possible when doing the following:

<form action="{% url submit_survey %}" class="uniForm" method="post">
    {% crispy first_form %}
    {% crispy second_form %}
</form>

But this is obviously dependent on the context names of the forms, but I can't find any resources that explain how to actually set the context variables of the forms that I want to display.

Below is an example of the top form and a possible bottom form:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit

class BusinessForm(forms.ModelForm):

    group_id = forms.ModelChoiceField(GroupModel.objects.all())

    def __init__(self, *args, **kwargs):
        super(BusinessForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.layout = Layout(
            'group_id',
            'contact_name',
            'business_name',
            'address_line_1',
            'address_line_2',
            'postcode',
            'telephone',
            'email',
            'web',
            ButtonHolder(
                Submit('submit', 'Add business', css_class='btn-primary')
            )
        )

    class Meta:
        model = BusinessModel
        fields = (
            'group_id',
            'contact_name',
            'business_name',
            'address_line_1',
            'address_line_2',
            'postcode',
            'telephone',
            'email',
            'web',
        )

class AttractionExtrasForm(forms.ModelForm):

    classification_id = forms.ModelChoiceField(AttractionClassModel.objects.all())

    def __init__(self, *args, **kwagrs):
        super(AttractionExtrasForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.layout = Layout(
            'classification_id',
        )

    class Meta:
        model = AttractionExtrasModel
        fields = (
            'classification_id',
        )

And the view:

class BusinessView(
    views.LoginRequiredMixin,
    views.FormValidMessageMixin,
    generic.edit.CreateView
):

    form_class = BusinessForm
    model = BusinessModel
    template_name = "businesses/business.html"
    success_url = reverse_lazy('businesses:add_business')
    from_valid_message = "You have successfully created a business."

    def form_valid(self, form):
        return super(BusinessView, self).form_valid(form)

And the template:

{% extends '_layouts/base.html' %}

{% load crispy_forms_tags %}

{% block title %}
Add business | {{ block.super }}
{% endblock title %}

{% block headline %}
<h1>Add business</h1>
{% endblock headline %}

{% block content %}
<form action="{% url add_business %}" method="post">
    {% crispy form %}
</form>
{% endblock content %}

That will display the normal form since it's only calling the form variable.

Does anybody know how to do this?

Cheers

解决方案

view:

 class BusinessView(...):
 ...

 def get_context_data(self, **kwargs):
      context = super(BusinessView, self).get_context_data(**kwargs)
      context['form_2'] = AttractionExtrasForm(instance=self.model())  # if createview
      # context['form_2'] = AttractionExtrasForm(instance=self.object)  # if updateview     

      return context

And you have to validate both separately

if form.is_valid() and form_2.is_valid():
    return self.form_valid(form, form_2)
else:
    return self.form_invalid(form, form_2)

If you models is connected (one have FK field to another)

def form_valid(self, form, form_2):
    if not self.object:  # createview
        self.object = form.save()
    else:  # updateview
        form.save()

    form_2.instance = self.object
    form_2.save()

    return HttpResponseRedirect(self.get_success_url())

def form_invalid(self, form, form_2):
    return self.render_to_response(
        self.get_context_data(
            form=form,
            form_2=form_2
        )
    )

And if you want many instances of form_2 can use inlineformset_factory https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#django.forms.models.BaseInlineFormSet

template:

<form method="post">{% csrf_token %}
    {% crispy form %}
    {% crispy form_2 %}
</form>

这篇关于将两种形式的脆皮形式上下文名称定义为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆