Crispy Forms: FormHelper for split forms / two columns same model2019 Community Moderator ElectionDefine crispy forms context names for two forms in oneAttributeError - type object 'Services' has no attribute 'service_price'Can't add field to ModelForm at __init__Promotion code with Django ModelsDjango modelformset order_by not workingInitial value is not working for ChoiceField on django-filters'NoneType' object is not subscriptable in using django smart selectsDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fielddjango how to hide specific form filed and loop data input

Is "cogitate" used appropriately in "I cogitate that success relies on hard work"?

3.5% Interest Student Loan or use all of my savings on Tuition?

Is there a way to make cleveref distinguish two environments with the same counter?

Why is there an extra space when I type "ls" on the Desktop?

Can I negotiate a patent idea for a raise, under French law?

What is the purpose of a disclaimer like "this is not legal advice"?

Is it appropriate to ask a former professor to order a book for me through an inter-library loan?

Can the Witch Sight warlock invocation see through the Mirror Image spell?

Is there stress on two letters on the word стоят

Computation logic of Partway in TikZ

Writing text next to a table

Did Amazon pay $0 in taxes last year?

Would those living in a "perfect society" not understand satire

What is this tube in a jet engine's air intake?

Can one live in the U.S. and not use a credit card?

Do black holes violate the conservation of mass?

Too soon for a plot twist?

Either of .... (Plural/Singular)

Why do phishing e-mails use faked e-mail addresses instead of the real one?

Was it really inappropriate to write a pull request for the company I interviewed with?

PTIJ: Who was the sixth set of priestly clothes for?

Under what conditions can the right to remain silent be revoked in the USA?

Is there a logarithm base for which the logarithm becomes an identity function?

Professor forcing me to attend a conference, I can't afford even with 50% funding



Crispy Forms: FormHelper for split forms / two columns same model



2019 Community Moderator ElectionDefine crispy forms context names for two forms in oneAttributeError - type object 'Services' has no attribute 'service_price'Can't add field to ModelForm at __init__Promotion code with Django ModelsDjango modelformset order_by not workingInitial value is not working for ChoiceField on django-filters'NoneType' object is not subscriptable in using django smart selectsDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fielddjango how to hide specific form filed and loop data input










1















My Template is divided into two columns.
I have only one Model but aiming for split a form into two, one part in the first column, another part in the second column. I aim for using FormHelper for Crispy Forms.



Available Documentation gives a cryptic hint but without any examples such attempt to an explanation falls a bit short.



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




Rendering several forms with helpers



Often we get asked: “How do you render two or more forms, with their
respective helpers, using % crispy % tag, without having tags
rendered twice?” Easy, you need to set form_tag helper property to
False in every helper:



self.helper.form_tag = False


Then you will have to write a little of html code surrounding the
forms:



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



UPDATE: This post explains the passus of the Crispy documentation
Define crispy forms context names for two forms in one



Below is my code. The two FormHelper divide the Model into two parts, first part with fields: ['car_model_make', 'status_is_secondhand']
second part with fields: ['seller', 'buyer']



What I have been looking for is a way to "call" upon a specific % crispy form %. Given the "help" documentation" such would look as % crispy product-modelform_1 % and % crispy product-modelform_2 % which does not work.



# 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">









share|improve this question




























    1















    My Template is divided into two columns.
    I have only one Model but aiming for split a form into two, one part in the first column, another part in the second column. I aim for using FormHelper for Crispy Forms.



    Available Documentation gives a cryptic hint but without any examples such attempt to an explanation falls a bit short.



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




    Rendering several forms with helpers



    Often we get asked: “How do you render two or more forms, with their
    respective helpers, using % crispy % tag, without having tags
    rendered twice?” Easy, you need to set form_tag helper property to
    False in every helper:



    self.helper.form_tag = False


    Then you will have to write a little of html code surrounding the
    forms:



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



    UPDATE: This post explains the passus of the Crispy documentation
    Define crispy forms context names for two forms in one



    Below is my code. The two FormHelper divide the Model into two parts, first part with fields: ['car_model_make', 'status_is_secondhand']
    second part with fields: ['seller', 'buyer']



    What I have been looking for is a way to "call" upon a specific % crispy form %. Given the "help" documentation" such would look as % crispy product-modelform_1 % and % crispy product-modelform_2 % which does not work.



    # 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">









    share|improve this question


























      1












      1








      1








      My Template is divided into two columns.
      I have only one Model but aiming for split a form into two, one part in the first column, another part in the second column. I aim for using FormHelper for Crispy Forms.



      Available Documentation gives a cryptic hint but without any examples such attempt to an explanation falls a bit short.



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




      Rendering several forms with helpers



      Often we get asked: “How do you render two or more forms, with their
      respective helpers, using % crispy % tag, without having tags
      rendered twice?” Easy, you need to set form_tag helper property to
      False in every helper:



      self.helper.form_tag = False


      Then you will have to write a little of html code surrounding the
      forms:



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



      UPDATE: This post explains the passus of the Crispy documentation
      Define crispy forms context names for two forms in one



      Below is my code. The two FormHelper divide the Model into two parts, first part with fields: ['car_model_make', 'status_is_secondhand']
      second part with fields: ['seller', 'buyer']



      What I have been looking for is a way to "call" upon a specific % crispy form %. Given the "help" documentation" such would look as % crispy product-modelform_1 % and % crispy product-modelform_2 % which does not work.



      # 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">









      share|improve this question
















      My Template is divided into two columns.
      I have only one Model but aiming for split a form into two, one part in the first column, another part in the second column. I aim for using FormHelper for Crispy Forms.



      Available Documentation gives a cryptic hint but without any examples such attempt to an explanation falls a bit short.



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




      Rendering several forms with helpers



      Often we get asked: “How do you render two or more forms, with their
      respective helpers, using % crispy % tag, without having tags
      rendered twice?” Easy, you need to set form_tag helper property to
      False in every helper:



      self.helper.form_tag = False


      Then you will have to write a little of html code surrounding the
      forms:



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



      UPDATE: This post explains the passus of the Crispy documentation
      Define crispy forms context names for two forms in one



      Below is my code. The two FormHelper divide the Model into two parts, first part with fields: ['car_model_make', 'status_is_secondhand']
      second part with fields: ['seller', 'buyer']



      What I have been looking for is a way to "call" upon a specific % crispy form %. Given the "help" documentation" such would look as % crispy product-modelform_1 % and % crispy product-modelform_2 % which does not work.



      # 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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 6 at 23:10







      Jaco

















      asked Mar 6 at 12:40









      JacoJaco

      1219




      1219






















          2 Answers
          2






          active

          oldest

          votes


















          1














          You can't have two __init__ methods and you don't need it actually. You may just enclose those two 'columns' inside two separate <div> tags with the help of FormHelper().



          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'
          )
          )


          Hope, this gives you the trick. Refer Layouts for more.






          share|improve this answer

























          • Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

            – Jaco
            Mar 6 at 13:35











          • May I know the purpose of those block and endblock inside form?

            – art06
            Mar 6 at 13:41











          • Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

            – Jaco
            Mar 6 at 13:50












          • Sorry, I don't get it. Can you update the post with the contents of your block tags?

            – art06
            Mar 6 at 14:16











          • sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

            – Jaco
            Mar 6 at 14:27


















          0














          This seems to work for now (mainly inspired from Define crispy forms context names for two forms in one but here I have created two new forms based upon a ModelForm): I wish I fully understood the solution better myself, but at least it works as intended.



          # 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 %





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023366%2fcrispy-forms-formhelper-for-split-forms-two-columns-same-model%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can't have two __init__ methods and you don't need it actually. You may just enclose those two 'columns' inside two separate <div> tags with the help of FormHelper().



            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'
            )
            )


            Hope, this gives you the trick. Refer Layouts for more.






            share|improve this answer

























            • Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

              – Jaco
              Mar 6 at 13:35











            • May I know the purpose of those block and endblock inside form?

              – art06
              Mar 6 at 13:41











            • Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

              – Jaco
              Mar 6 at 13:50












            • Sorry, I don't get it. Can you update the post with the contents of your block tags?

              – art06
              Mar 6 at 14:16











            • sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

              – Jaco
              Mar 6 at 14:27















            1














            You can't have two __init__ methods and you don't need it actually. You may just enclose those two 'columns' inside two separate <div> tags with the help of FormHelper().



            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'
            )
            )


            Hope, this gives you the trick. Refer Layouts for more.






            share|improve this answer

























            • Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

              – Jaco
              Mar 6 at 13:35











            • May I know the purpose of those block and endblock inside form?

              – art06
              Mar 6 at 13:41











            • Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

              – Jaco
              Mar 6 at 13:50












            • Sorry, I don't get it. Can you update the post with the contents of your block tags?

              – art06
              Mar 6 at 14:16











            • sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

              – Jaco
              Mar 6 at 14:27













            1












            1








            1







            You can't have two __init__ methods and you don't need it actually. You may just enclose those two 'columns' inside two separate <div> tags with the help of FormHelper().



            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'
            )
            )


            Hope, this gives you the trick. Refer Layouts for more.






            share|improve this answer















            You can't have two __init__ methods and you don't need it actually. You may just enclose those two 'columns' inside two separate <div> tags with the help of FormHelper().



            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'
            )
            )


            Hope, this gives you the trick. Refer Layouts for more.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 6 at 14:20

























            answered Mar 6 at 13:27









            art06art06

            796414




            796414












            • Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

              – Jaco
              Mar 6 at 13:35











            • May I know the purpose of those block and endblock inside form?

              – art06
              Mar 6 at 13:41











            • Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

              – Jaco
              Mar 6 at 13:50












            • Sorry, I don't get it. Can you update the post with the contents of your block tags?

              – art06
              Mar 6 at 14:16











            • sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

              – Jaco
              Mar 6 at 14:27

















            • Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

              – Jaco
              Mar 6 at 13:35











            • May I know the purpose of those block and endblock inside form?

              – art06
              Mar 6 at 13:41











            • Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

              – Jaco
              Mar 6 at 13:50












            • Sorry, I don't get it. Can you update the post with the contents of your block tags?

              – art06
              Mar 6 at 14:16











            • sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

              – Jaco
              Mar 6 at 14:27
















            Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

            – Jaco
            Mar 6 at 13:35





            Thanks, given your answer, I have updated my question. Meanwhile it would work as you suggest, but in my case the actual layout is unfortunately much more complex and I would need a "block" to insert. But, if this is the only solution, I would need to place all that formatting into the div.

            – Jaco
            Mar 6 at 13:35













            May I know the purpose of those block and endblock inside form?

            – art06
            Mar 6 at 13:41





            May I know the purpose of those block and endblock inside form?

            – art06
            Mar 6 at 13:41













            Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

            – Jaco
            Mar 6 at 13:50






            Block above was referring to "insert a form object, such as % crispy form %" (sry for confusing terms). The idea of using Blocks in my template was as I removed the Tags 'self.helper.form_tag = False' and had a manual form in my second column, this was the way I manage to save both Forms. So, Block col8 is my left column, and Block col4 is my right column. In each block there is a form, both forms come from the same Model and I would need to save them both at the same time.

            – Jaco
            Mar 6 at 13:50














            Sorry, I don't get it. Can you update the post with the contents of your block tags?

            – art06
            Mar 6 at 14:16





            Sorry, I don't get it. Can you update the post with the contents of your block tags?

            – art06
            Mar 6 at 14:16













            sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

            – Jaco
            Mar 6 at 14:27





            sry for missunderstanding, added the the content, essentially a list of foldable cards, each contains form fields (from the same model)

            – Jaco
            Mar 6 at 14:27













            0














            This seems to work for now (mainly inspired from Define crispy forms context names for two forms in one but here I have created two new forms based upon a ModelForm): I wish I fully understood the solution better myself, but at least it works as intended.



            # 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 %





            share|improve this answer





























              0














              This seems to work for now (mainly inspired from Define crispy forms context names for two forms in one but here I have created two new forms based upon a ModelForm): I wish I fully understood the solution better myself, but at least it works as intended.



              # 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 %





              share|improve this answer



























                0












                0








                0







                This seems to work for now (mainly inspired from Define crispy forms context names for two forms in one but here I have created two new forms based upon a ModelForm): I wish I fully understood the solution better myself, but at least it works as intended.



                # 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 %





                share|improve this answer















                This seems to work for now (mainly inspired from Define crispy forms context names for two forms in one but here I have created two new forms based upon a ModelForm): I wish I fully understood the solution better myself, but at least it works as intended.



                # 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 %






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 6 at 23:15

























                answered Mar 6 at 23:09









                JacoJaco

                1219




                1219



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023366%2fcrispy-forms-formhelper-for-split-forms-two-columns-same-model%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page