django-shapeshifter

A common problem in Django is how to have a view, especially a class-based view that can display and process multiple forms at once. django-shapeshifter aims to make this problem much more trivial.

Right now, django-shapeshifter can handle any (well, theoretically) number of forms in a single view. A view class is provided for multiple standard forms or model forms. To mix and match these form types, you’ll need to do a little extra work. Here’s how to use the package:

Installation

$ pip install django-shapeshifter

You should not need to add shapeshifter to your INSTALLED_APPS.

Usage

You use django-shapeshifter just like you use Django’s built-in class-based views. You should be able to use the provided views with most mixins you’re already using in your project, such as LoginRequiredMixin. Certain mixins may have to be refactored, such as SuccessMessageMixin, which is trigged on the form_valid() method.

Let’s look at using the view with a few standard forms:

interests/views.py

from django.urls import reverse_lazy

from shapeshifter.views import MultiFormView

from . import forms


class InterestFormsView(MultiFormView):
    form_classes = (forms.ContactForm, forms.InterestsForm, forms.GDPRForm)
    template_name = 'interests/forms.html'
    success_url = reverse_lazy('interests:thanks')

But what do you need to do in the template? The view’s context will contain a new member, forms, that you can iterate over to display each form:

interests/templates/interests/forms.html

<div class="highlight highlight-text-html-basic position-relative" data-snippet-clipboard-copy-content="{% extends 'layout.html' %}

{% block content %}

Please fill out your interests below!

{% csrf_token %}
{% for form in forms %}
{{ form.as_p }}
{% endfor %}

{% endblock content %}
“>

{% extends 'layout.html' %}

{% block content %}
<h3>Please fill out your interests below!</h3>

<form method="POST">
{% csrf_token %}
{% for form in forms %}
    {{ form.as_p }}
{% endfor %}
    <input type="submit" value="Save" />
</form>
{% endblock content %}