脆皮形式:FormHelper用于拆分形式/两列相同型号

问题描述 投票:1回答:2

我的模板分为两列。我只有一个模型,但目的是将表单拆分为两个,第一列中的一个部分,第二列中的另一个部分。我的目标是使用FormHelper for Crispy Forms。

可用的文档提供了一个神秘的暗示,但没有任何示例,这种尝试解释有点短。

https://django-crispy-forms.readthedocs.io/en/d-0/tags.html#rendering-several-forms-with-helpers

使用帮助器呈现多个表单

通常我们会被问到:“如何使用{%crispy%}标记,使用{%crispy%}标记呈现两个或多个表单,而不会使标记呈现两次?”很简单,您需要在每个帮助器中将form_tag helper属性设置为False:

self.helper.form_tag = False

然后你将不得不写一些围绕表格的HTML代码:

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

更新:这篇文章解释了Crispy文档Define crispy forms context names for two forms in one的传递

以下是我的代码。两个FormHelper将模型分为两部分,第一部分用字段:['car_model_make', 'status_is_secondhand']第二部分用字段:['seller', 'buyer']

我一直在寻找的是一种“召唤”特定{% crispy form %}的方法。鉴于“帮助”文档“这样看起来像{% crispy product-modelform_1 %}{% crispy product-modelform_2 %}不起作用。

# models.py
class Product(models.Models):
    car_model_make = models.CharField(default='B', max_length=1, blank=True, choices=CAR_TYPE)
    status_is_secondhand = models.BooleanField(blank=True)
    seller = models.CharField(max_length=50, blank=True, choices=SELLER_TYPE)
    buyer = models.CharField(max_length=50, blank=True, choices=BUYER_TYPE)

# forms.py
class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ('__all__')

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.form_id = 'product-modelform'
        self.helper.form_tag = False


        model = 'car_model_make'
        secondhand = 'status_is_secondhand'

        self.fields[model].label = "Model"
        self.fields[secondhand].label = "Is Secondhand"

        self.helper.layout = Layout(
            Field(model),
            Field(secondhand),
            )

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.form_id = 'product-modelform'
        self.helper.form_tag = False


        seller = 'seller'
        buyer = 'buyer'

        self.fields[seller].label = "Seller"
        self.fields[buyer].label = "buyer"

        self.helper.layout = Layout(
            Field(seller),
            Field(buyer),
            )

# views.py
class ProductFormView(FormView):
    form_class = ProductForm

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

    def get_success_url(self):
        return reverse('index')

# urls.py
urlpatterns = [
    path('', index, name='index'),
    path('product/', ProductFormView.as_view(template_name='product/product.html'),


# html template

{% extends "product/base.html" %}
{% load crispy_forms_tags %}

{% block col8_content %}
<form id="product-modelform" method="post">
    {% csrf_token %}
    {% crispy form %}
    {% endblock col8_content %}
    {% block col4_content %}   
</form>
    {% endblock col4_content %}
    <input type="submit" value="Submit">
python django django-forms django-crispy-forms
2个回答
1
投票

你不能有两个__init__方法,你实际上并不需要它。您可以在FormHelper()的帮助下将这两个“列”括在两个单独的<div>标记内。

def __init__(self, *args, **kwargs):
      super(ProductForm, self).__init__(*args, **kwargs)
      self.helper = FormHelper()
      self.helper.form_class = 'form-horizontal'
      self.helper.label_class = 'col-sm-4'
      self.helper.field_class = 'col-sm-8'
      self.helper.form_id = 'product-modelform'
      self.helper.form_tag = False
      self.helper.layout = Layout(
      Div(
        Div('car_model_make','status_is_secondhand', css_class='col-lg-6 col-md-6 col-sm-12'),
        Div('seller','buyer', css_class='col-lg-6 col-md-6 col-sm-12'),
        css_class='row'
        )
      )

希望,这会给你一个技巧。请参阅Layouts了解更多信息。


0
投票

这似乎现在有用(主要是受到Define crispy forms context names for two forms in one的启发,但在这里我创建了两个基于ModelForm的新表单):我希望自己能够更好地理解解决方案,但至少它可以按预期工作。

# models.py
class Product(models.Models):
    car_model_make = models.CharField(default='B', max_length=1, blank=True, choices=CAR_TYPE)
    status_is_secondhand = models.BooleanField(blank=True)
    seller = models.CharField(max_length=50, blank=True, choices=SELLER_TYPE)
    buyer = models.CharField(max_length=50, blank=True, choices=BUYER_TYPE)

# forms.py
class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ('__all__')

class CarForm(ProductForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.form_tag = False
        self.helper.add_input(Submit('submit', 'Submit'))

        model = 'car_model_make'
        secondhand = 'status_is_secondhand'

        self.fields[model].label = "Model"
        self.fields[secondhand].label = "Is Secondhand"

        self.helper.layout = Layout(
            Field(model),
            Field(secondhand),
            )

class TransactionForm(ProductForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.form_tag = False


        seller = 'seller'
        buyer = 'buyer'

        self.fields[seller].label = "Seller"
        self.fields[buyer].label = "buyer"

        self.helper.layout = Layout(
            Field(Seller),
            Field(buyer),
            )

# views.py
class ProductFormView(FormView):
    form_class = CarForm
    model = Product

    def get_context_data(self, **kwargs):
        context = super(ProductFormView, self).get_context_data(**kwargs)
        context['form_2'] = TransactionForm(instance=self.model())
        return context

    def form_valid(self, form):
        self.object = form.save()
        return HttpResponseRedirect(self.get_success_url())

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

    def get_success_url(self):
        return reverse('index')

# urls.py
urlpatterns = [
    path('', index, name='index'),
    path('product/', ProductFormView.as_view(template_name='product/product.html'),


# html template

{% extends "product/base.html" %}
{% load crispy_forms_tags %}

{% block col8_content %}
<form id="product-modelform" method="post">
    {% csrf_token %}
    {% crispy form %}
    {% endblock col8_content %}
    {% block col4_content %}
    {% crispy form_2 %}
</form>
    {% endblock col4_content %}
© www.soinside.com 2019 - 2024. All rights reserved.