Coder Social home page Coder Social logo

tiesjan / django-convenient-formsets Goto Github PK

View Code? Open in Web Editor NEW
15.0 4.0 4.0 155 KB

Django dynamic formsets made convenient for users and developers alike.

Home Page: https://pypi.org/project/django-convenient-formsets/

License: BSD 3-Clause "New" or "Revised" License

Python 35.46% JavaScript 27.16% HTML 37.38%
django-formsets django formsets python javascript django-forms

django-convenient-formsets's Introduction

Django Convenient Formsets

Python unit tests End-to-end tests Linters TestingBot Test Status

This Django app aims to make dynamic formsets convenient for users and developers alike. It extends Django's built-in formset classes and includes support for adding, deleting and ordering of forms in the browser. JavaScript events are dispatched when forms are added, deleted or reordered, for executing custom logic.

Supported platforms

  • Django: 4.2+
  • Python: 3.8+
  • Tested desktop browsers: latest Chrome, latest Firefox, latest Edge, latest Opera, latest Safari

Other platform versions may work, but are not actively tested.

Installation

  1. Install using pip:

    $ pip install django-convenient-formsets
  2. Add to INSTALLED_APPS:

    INSTALLED_APPS = [
        # ...
        'convenient_formsets'
    ]

Quick start

  1. Create a formset in your Python code:

    from convenient_formsets import ConvenientBaseFormSet
    from django import forms
    
    
    class EmailForm(forms.Form):
        email = forms.EmailField()
    
    EmailFormSet = forms.formset_factory(
        EmailForm,
        formset=ConvenientBaseFormSet,
        can_delete=True,
        can_order=True,
    )
    
    email_formset = EmailFormSet(prefix='email-formset')
  2. Render formset in your template and add JavaScript code for initialization:

    <!doctype html>
    <html>
    <head>
        <!-- Include the formset's media -->
        {{ email_formset.media }}
    
        <!-- Initialize a ConvenientFormset -->
        <script>
            window.addEventListener('load', function(event) {
                new ConvenientFormset({
                    'formsetPrefix': '{{ email_formset.prefix }}',
                    'formsContainerSelector': '#email-formset #email-forms-container',
                    'formSelector': '.email-form',
    
                    'canAddForms': true,
                    'addFormButtonSelector': '#email-formset #add-form-button',
                    'emptyFormTemplateSelector': '#email-formset #empty-form-template',
    
                    'canDeleteForms': true,
                    'deleteFormButtonSelector': '.delete-form-button',
    
                    'canOrderForms': true,
                    'moveFormDownButtonSelector': '.move-form-down-button',
                    'moveFormUpButtonSelector': '.move-form-up-button',
                });
            });
        </script>
    </head>
    
    <body>
        <!-- Render formset using the following basic structure -->
        <div id="email-formset">
            <div id="email-forms-container">
                {% for email_form in email_formset.forms %}
                <div class="email-form">
                    {{ email_form.email }}
                    {% if email_formset.can_delete %}
                        {{ email_form.DELETE }}
                        <input type="button" class="delete-form-button" value="Delete">
                    {% endif %}
                    {% if email_formset.can_order %}
                        {{ email_form.ORDER }}
                        <input type="button" class="move-form-up-button" value="Move up">
                        <input type="button" class="move-form-down-button" value="Move down">
                    {% endif %}
                </div>
                {% endfor %}
            </div>
            <div><input type="button" id="add-form-button" value="Add another"></div>
            <template id="empty-form-template">
                <div class="email-form">
                    {{ email_formset.empty_form.email }}
                    {% if email_formset.can_delete %}
                        <input type="button" class="delete-form-button" value="Delete">
                    {% endif %}
                    {% if email_formset.can_order %}
                        {{ email_form.ORDER }}
                        <input type="button" class="move-form-up-button" value="Move up">
                        <input type="button" class="move-form-down-button" value="Move down">
                    {% endif %}
                </div>
            </template>
            {{ email_formset.management_form }}
        </div>
    </body>
    </html>

Usage

Server side

The Python classes ConvenientBaseFormSet, ConvenientBaseModelFormSet and ConvenientBaseInlineFormSet extend Django's built-in BaseFormSet, BaseModelFormSet and BaseInlineFormSet by:

  • Overriding deletion_widget for the DELETE field and ordering_widget for the ORDER field. They default to the forms.HiddenInput widget in order to hide them from the user.
  • Including the JavaScript file in the formset's media attribute required for dynamic formsets.

Client side

See the example in the Quick start guide above on how to render the formset in your HTML template. Feel free to add some intermediate DOM elements if it suits your template better, as long as you stick to the basic structure shown above.

It is important that both the visible forms and the empty form follow the same structure. A form also needs to be contained inside a single parent element, denoted by the formSelector parameter:

<!-- Visible forms inside forms container -->
<div id="email-forms-container">
    <div class="email-form">
        <!-- Form -->
    </div>
</div>

<!-- Empty form inside template element -->
<template id="empty-form-template">
    <div class="email-form">
        <!-- Form -->
    </div>
</template>

Configuration

Creating an instance of the JavaScript constructor function ConvenientFormset allows a user to add, delete and reorder forms within the rendered formset. When a user makes changes, the management form is updated accordingly. The constructor function can be passed the parameters outlined below. In case initialization fails, check the browser console for some helpful output.

GENERAL
formsetPrefix
The formset's "prefix" attribute (required).
formsContainerSelector
CSS selector for the DOM element that contains all the forms (required).
formSelector
CSS selector for each form within "formsContainerSelector" (required).

ADDING FORMS
canAddForms
Enables adding of new forms (default: true).
addFormButtonSelector
CSS selector for the DOM element that may be clicked to add an empty form (required if "canAddForms" is set).
emptyFormTemplateSelector
CSS selector for the empty form <template> element (required if "canAddForms" is set).
hideAddFormButtonOnMaxForms
Hides the add button when reaching the maximum number of forms, by applying the "hidden" HTML attribute (default: true).

DELETING FORMS
canDeleteForms
Enables deleting of forms (default: false).
deleteFormButtonSelector
CSS selector for the DOM element within "formSelector" that may be clicked to delete a form (required if "canDeleteForms" is set).

ORDERING FORMS
canOrderForms
Enables ordering of forms (default: false).
moveFormDownButtonSelector
CSS selector for the DOM element within "formSelector" that may be clicked to move a form down among the visible forms (required if "canOrderForms" is set).
moveFormUpButtonSelector
CSS selector for the DOM element within "formSelector" that may be clicked to move a form up among the visible forms (required if "canOrderForms" is set).

Events

When adding, deleting or reordering forms, custom JavaScript events are dispatched to allow for executing custom JavaScript code:

convenient_formset:added
Dispatched when a form is added to the formset.
convenient_formset:removed
Dispatched when a form is removed to the formset.
convenient_formset:movedDown
Dispatched when a form is moved downwards while reordering forms inside the formset.
convenient_formset:movedUp
Dispatched when a form is moved upwards while reordering forms inside the formset.

All events will contain the formsetPrefix parameter value in the event's detail property.

These events can be handled in the following way:

document.addEventListener('convenient_formset:added', (event) => {
    if (event.detail.formsetPrefix === 'email-formset') {
        // Handle event for a specific formset on the webpage
    }
});

document.addEventListener('convenient_formset:removed', (event) => {
    // Handle event for any formset on the webpage
});

Internals

Form deletion is handled in either of the following ways:

  1. If a form includes a DELETE field, the field's value is updated and the form will be hidden by applying the "hidden" HTML attribute. The deletion will then be handled server side.
  2. If the form does not include a DELETE field, the form is removed from the DOM altogether and will not be submitted to the server.

Form ordering is handled by moving visible forms above the previous (up) and below the next (down) for visual feedback, and by swapping the values of their ORDER fields for the server side. This means that the original values are kept, even when in-between forms are deleted. New forms will see the initial value for their ORDER field set to the last visible form's ORDER field value + 1, as they're added to the bottom of all forms.

License

The scripts and documentation in this project are released under the BSD-3-Clause License.

django-convenient-formsets's People

Contributors

cleitondelima avatar joahim avatar tiesjan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-convenient-formsets's Issues

Buttons of the forms use the same HTML ID

The deleteFormButtonSelector, moveFormDownButtonSelector and the moveFormUpButtonSelector in the example provided in the README seem to use the same HTML IDs. In other terms, if a FormSet gathers N forms, the #delete-form-button CSS selector (for instance) will correspond to N elements.

While it does 'work', it's not valid HTML (see here) and it can lead to various issues if other parts of the code take for granted that these IDs are unique.

Is there a way to use this extension while avoiding that pitfall?

I suggest to update at least the README.

django-convenient-formsets v2.0.

Change prefix throughout html

In empty-form, if I've been using form.prefix (__prefix__) elsewhere, wouldn't it be better to update them too.
Think that the index update could be done via string and not traversing all elements.

Came across this, in this case I have a custom widget:
image

Some ideas.

  • Transform empty-form into string, apply prefix change and create new form.
  • The empty-form could be inside a <template>...</template> block? (avoids executing some third-party script in some form class)

Index of the new form is not updating

I am having issue where newly added forms dont have the index, it just has prefix text on it. I initially had crispy forms but then removed it and tested without crispy form and seems to have the same issue.

Not sure if I am missing anything on config.

I do have the prefix attribute in formsetOptions
'formsetPrefix': '{{ formset.prefix }}',

PS: Thank you for this amazing library. 🙏

Uncaught ReferenceError: ConvenientFormSet is not defined

Hi,
trying to use your Module but don't see any forms.
if i copy paste your code i get the Error:

NameError: name 'ConvenientBaseFormset' is not defined. Did you mean: 'ConvenientBaseFormSet'?

when i change it to "ConvenientBaseFormSet" it works, but don't see any form.
In my Console i get the error:

Uncaught ReferenceError: ConvenientFormset is not defined

What's wrong here?

Why is only django 4.2+ supported?

Reviewing the implementation that the package has and seeing that the core is mainly javascript, makes me wonder why only support Django 4.2+? Isn't it better to have greater backward compatibility between versions?

This is because currently I would like to use the package in its 2.0 version, but the dependencies cause me problems (I cannot upgrade to Django 4.2 due to other packages). I would consider that if it does not affect the package, modify the dependency with Django 4.2 and indicate that it is compatible with previous versions

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.