Add a dynamic form to a django formset using javascript in a right way

后端 未结 1 1621
逝去的感伤
逝去的感伤 2020-12-12 17:28

How to add a dynamic form to a django formset in templates without annoying copies of html template output?

I have a formset with unknown count of result forms, and

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 18:06

    This self-answer is based on this post by Nick Lang, but we are going to simplify this way and we don't need to copy/paste whole form html anymore.

    We have an inline formset which is created in a view like this:

    items_formset = inlineformset_factory(Parent, Item, form=ItemForm, extra=1)
    item_forms = items_formset()  
    

    Next, we need to create a template for out formset form, we can do it using empty_form property of formset instance, which generates a html form template where every "id" number of a form is replaced by __prefix__ string, for example:

     {% crispy item_forms.empty_form item_forms.form.helper %} #}
    -->  
    

    So, first we need to replace this __prefix__ by an id and add a form using this template.
    Here is a form template code fragment, which we can use to create new elements:

    
    

    Then we need to display main part of the form:

    {% csrf_token %} {{ item_forms.management_form }}
    {% for item_form in item_forms %}
    {{ item_form.id }} {{ item_form.as_p }} {# {% crispy item_form %} #}
    {% endfor %}
    Add Item

    Finally we need to add some JS (jquery, tested with 1.9.1 and 2.1.0) to add a next formset form. Note we will not use underscore.js, since it's unneeded in this case: just str.replace to replace __prefix__ by next "id" number)

    
    

    That's all, just click on "Add Item" button, and a new formset item will appear.

    Be sure to replace this sample by your app_name/model_name.

    0 讨论(0)
提交回复
热议问题