### Install Tox for Testing Source: https://github.com/jazzband/django-formtools/blob/master/README.rst To run tests for django-formtools, first install Tox. Then, navigate to the project's root directory and execute the 'tox' command. ```bash $ git clone https://github.com/jazzband/django-formtools $ cd django-formtools $ tox ``` -------------------------------- ### Install django-formtools with pip Source: https://github.com/jazzband/django-formtools/blob/master/docs/index.md Use pip to install the django-formtools package. This is the recommended method for installation. ```bash pip install django-formtools ``` -------------------------------- ### Providing initial data for WizardView forms Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Illustrates how to provide initial data for wizard forms using `initial_dict`. This example is illustrative and requires an HttpRequest. ```python >>> from myapp.forms import ContactForm1, ContactForm2 >>> from myapp.views import ContactWizard >>> initial = { ... '0': {'subject': 'Hello', 'sender': 'user@example.com'}, ... '1': {'message': 'Hi there!'} ... } >>> # This example is illustrative only and isn't meant to be run in >>> # the shell since it requires an HttpRequest to pass to the view. >>> wiz = ContactWizard.as_view([ContactForm1, ContactForm2], initial_dict=initial)(request) >>> form1 = wiz.get_form('0') >>> form2 = wiz.get_form('1') >>> form1.initial {'sender': 'user@example.com', 'subject': 'Hello'} >>> form2.initial {'message': 'Hi there!'} ``` -------------------------------- ### Basic WizardView Setup with as_view() Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Use this snippet to set up a basic wizard by passing a list of form classes directly to the WizardView's as_view() method in your urls.py. ```python from django.path import path from myapp.forms import ContactForm1, ContactForm2 from myapp.views import ContactWizard urlpatterns = [ path('contact/', ContactWizard.as_view([ContactForm1, ContactForm2])), ] ``` -------------------------------- ### WizardView with Different Template per Form Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This example demonstrates how to use different templates for each step of a wizard by overriding the get_template_names method. It also shows how to define form steps with names and conditions. ```python from django.http import HttpResponseRedirect from formtools.wizard.views import SessionWizardView FORMS = [("address", myapp.forms.AddressForm), ("paytype", myapp.forms.PaymentChoiceForm), ("cc", myapp.forms.CreditCardForm), ("confirmation", myapp.forms.OrderForm)] TEMPLATES = {"address": "checkout/billingaddress.html", "paytype": "checkout/paymentmethod.html", "cc": "checkout/creditcard.html", "confirmation": "checkout/confirmation.html"} def pay_by_credit_card(wizard): """Return true if user opts to pay by credit card""" # Get cleaned data from payment step cleaned_data = wizard.get_cleaned_data_for_step('paytype') or {'method': 'none'} # Return true if the user selected credit card return cleaned_data['method'] == 'cc' class OrderWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): do_something_with_the_form_data(form_list) return HttpResponseRedirect('/page-to-redirect-to-when-done/') ... ``` ```python urlpatterns = [ path('checkout/', OrderWizard.as_view(FORMS, condition_dict={'cc': pay_by_credit_card})), ] ``` ```python class OrderWizard(WizardView): condition_dict = {'cc': pay_by_credit_card} ``` -------------------------------- ### WizardView.get_context_data() Example for Step-Specific Data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Extends the default context data to include additional variables for a specific wizard step. Ensure to call the superclass method first. ```python def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context ``` -------------------------------- ### WizardView Setup with Class Attribute form_list Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Alternatively, define the list of forms as a class attribute named 'form_list' within your wizard view class. ```python class ContactWizard(WizardView): form_list = [ContactForm1, ContactForm2] ``` -------------------------------- ### WizardView.render Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Called after GET or POST requests are handled. Allows customization of the HTTP response type. ```APIDOC ## WizardView.render(form, **kwargs) ### Description Invoked after GET or POST request handling. Useful for altering the HTTP response type. ### Method This method is part of the WizardView class. ### Parameters * **form** - The form instance to render (optional). * **kwargs** - Additional keyword arguments. ### Default implementation: ```python def render(self, form=None, **kwargs): form = form or self.get_form() context = self.get_context_data(form=form, **kwargs) return self.render_to_response(context) ``` ``` -------------------------------- ### Wizard form template example Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This Django template demonstrates how to render wizard forms, including step navigation, form media, and management forms. It utilizes the `wizard` object provided by the WizardView context. ```html+django {% extends "base.html" %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %}

Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}

{% csrf_token %} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %}
{% if wizard.steps.prev %} {% endif %}
{% endblock %} ``` -------------------------------- ### WizardView `done` method: Redirect after processing Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This example demonstrates how to implement the `done` method to process form data and then redirect the user to a different page. This is a common practice for Web citizens after a POST request. ```python from django.http import HttpResponseRedirect from formtools.wizard.views import SessionWizardView class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): do_something_with_the_form_data(form_list) return HttpResponseRedirect('/page-to-redirect-to-when-done/') ``` -------------------------------- ### Get Step URL Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Provides the default implementation for the get_step_url method in NamedUrlWizardView, which constructs the URL for a given step. ```python def get_step_url(self, step): return reverse(self.url_name, kwargs={'step': step}) ``` -------------------------------- ### WizardView.get_form() Example for Adding User Attribute Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Overrides the form construction to add a 'user' attribute to the form instance for a specific step. It ensures the step is determined if not provided. ```python def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current if step == '1': form.user = self.request.user return form ``` -------------------------------- ### Default WizardView render Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Called after GET or POST requests are handled. Allows modification of the HTTP response type. ```python def render(self, form=None, **kwargs): form = form or self.get_form() context = self.get_context_data(form=form, **kwargs) return self.render_to_response(context) ``` -------------------------------- ### Custom WizardView with file_storage Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Example of a custom WizardView subclass that includes `file_storage` for handling FileFields. It uses Django's FileSystemStorage to store uploaded photos. ```python from django.conf import settings from django.core.files.storage import FileSystemStorage class CustomWizardView(WizardView): ... file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) ``` -------------------------------- ### Define Contact Form Wizard Steps Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Define Django Form classes for each step of a multi-page form wizard. This example shows two forms: one for sender information and another for the message. ```default from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() class ContactForm2(forms.Form): message = forms.CharField(widget=forms.Textarea) ``` -------------------------------- ### Migrate WizardView import from django.contrib.formtools Source: https://github.com/jazzband/django-formtools/blob/master/docs/index.md Update import statements when migrating from the old django.contrib.formtools to the third-party django-formtools package. This example shows the change for WizardView. ```python from django.contrib.formtools.wizard.views import WizardView ``` ```python from formtools.wizard.views import WizardView ``` -------------------------------- ### Configure Wizard URLs with Condition Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Sets up URL routing for the contact wizard, including passing the form list and the condition dictionary to the as_view method. ```python from django.urls import path from myapp.forms import ContactForm1, ContactForm2 from myapp.views import ContactWizard, show_message_form_condition contact_forms = [ContactForm1, ContactForm2] urlpatterns = [ path('contact/', ContactWizard.as_view(contact_forms, condition_dict={'1': show_message_form_condition} )), ] ``` -------------------------------- ### WizardView Default get_form_initial Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This is the default implementation for the get_form_initial method, which returns initial data for a given step from the wizard's initial_dict. An empty dictionary is returned if no initial data is found for the step. ```python def get_form_initial(self, step): return self.initial_dict.get(step, {}) ``` -------------------------------- ### List Available Tox Environments Source: https://github.com/jazzband/django-formtools/blob/master/README.rst To view all available test environments managed by Tox, use the '-l' option with the 'tox' command. This lists combinations of Python and Django versions. ```bash $ tox -l ``` -------------------------------- ### WizardView.get_form Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Constructs and returns the form instance for a specified step, optionally accepting data and files. Allows for customization by adding attributes or modifying the form instance before it's returned. ```APIDOC ## WizardView.get_form(step=None, data=None, files=None) ### Description This method constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. If you override `get_form`, however, you will need to set `step` yourself using `self.steps.current` as in the example below. The method gets three arguments: * `step` – The step for which the form instance should be generated. * `data` – Gets passed to the form’s data argument * `files` – Gets passed to the form’s files argument You can override this method to add extra arguments to the form instance. ### Method `get_form(self, step=None, data=None, files=None)` ### Parameters #### Path Parameters - **step** (string) - Optional - The step for which the form instance should be generated. Defaults to the current step if None. - **data** (dict) - Optional - Data to be passed to the form's `data` argument. - **files** (dict) - Optional - Files to be passed to the form's `files` argument. ### Response #### Success Response (Form) - Returns the constructed form instance for the specified step. ``` -------------------------------- ### WizardView.render_goto_step Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Handles the logic for changing the wizard to a non-sequential step. It stores the requested step in storage and then renders the new step, with an option to override for storing current step data. ```APIDOC ## WizardView.render_goto_step(step, goto_step, **kwargs) ### Description This method is called when the step should be changed to something else than the next step. By default, this method just stores the requested step `goto_step` in the storage and then renders the new step. If you want to store the entered data of the current step before rendering the next step, you can overwrite this method. ### Method `render_goto_step(self, step, goto_step, **kwargs)` ### Parameters #### Path Parameters - **step** (string) - Required - The current step. - **goto_step** (string) - Required - The step to navigate to. - **kwargs** - Optional - Additional keyword arguments. ### Response #### Success Response (HttpResponse) - Renders the specified `goto_step`. ``` -------------------------------- ### Configure Named URL Wizard Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Sets up URL routing for a wizard using NamedUrlWizardView, defining named steps and associating them with forms. ```python from django.urls import path, re_path from myapp.forms import ContactForm1, ContactForm2 from myapp.views import ContactWizard named_contact_forms = ( ('contactdata', ContactForm1), ('leavemessage', ContactForm2), ) contact_wizard = ContactWizard.as_view(named_contact_forms, url_name='contact_step', done_step_name='finished') urlpatterns = [ re_path(r'^contact/(?P.+)/$', contact_wizard, name='contact_step'), path('contact/', contact_wizard, name='contact'), ] ``` -------------------------------- ### WizardView.get_prefix() Default Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Generates a default prefix for storage backends based on the wizard's class name. This helps in separating data for different wizard instances. ```python def get_prefix(self, request, *args, **kwargs): # use the lowercase underscore version of the class name return normalize_name(self.__class__.__name__) ``` -------------------------------- ### WizardView.process_step_files() Default Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Processes form files before they are stored. The default implementation returns the form's files dictionary. ```python def process_step_files(self, form): return self.get_form_step_files(form) ``` -------------------------------- ### WizardView.initial_dict Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Provides initial data for wizard forms via a dictionary mapping steps to initial data dictionaries. Can also be a class attribute. ```APIDOC ## WizardView.initial_dict ### Description Optional keyword argument or class attribute to provide initial data for wizard forms. Maps step identifiers to dictionaries of initial data. ### Usage Example: ```python initial = { '0': {'subject': 'Hello', 'sender': 'user@example.com'}, '1': {'message': 'Hi there!'} } # wiz = ContactWizard.as_view([ContactForm1, ContactForm2], initial_dict=initial)(request) ``` ``` -------------------------------- ### WizardView.get_form_kwargs() Default Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Returns an empty dictionary for keyword arguments when instantiating a form. This is the default behavior. ```python def get_form_kwargs(self, step): return {} ``` -------------------------------- ### Default WizardView get_form_step_files Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Returns the files associated with a form. Use this to manipulate files before they are stored. ```python def get_form_step_files(self, form): return form.files ``` -------------------------------- ### WizardView.get_prefix Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Generates a unique prefix for storage backends, enabling distinct data storage for multiple wizard instances within the same backend. The default implementation uses a normalized version of the class name. ```APIDOC ## WizardView.get_prefix(request, *args, **kwargs) ### Description This method returns a prefix for use by the storage backends. Backends use the prefix as a mechanism to allow data to be stored separately for each wizard. This allows wizards to store their data in a single backend without overwriting each other. You can change this method to make the wizard data prefix more unique to, e.g. have multiple instances of one wizard in one session. *Versionchanged* Changed in version 1.0: The `request` parameter was added. ### Method `get_prefix(self, request, *args, **kwargs)` ### Parameters #### Path Parameters - **request** (HttpRequest) - Required - The incoming HTTP request. - **args** - Optional - Additional positional arguments. - **kwargs** - Optional - Additional keyword arguments. ### Response #### Success Response (string) - Returns a string representing the storage prefix for the wizard. ``` -------------------------------- ### Configure URLconf for FormPreview Source: https://github.com/jazzband/django-formtools/blob/master/docs/preview.md Point a URL to an instance of your FormPreview subclass, passing the relevant Form or ModelForm class to its constructor. This sets up the endpoint for the form preview workflow. ```python from django import forms from myapp.forms import SomeModelForm from myapp.preview import SomeModelFormPreview # ... and add the following line to the appropriate model in your URLconf: # path('post/', SomeModelFormPreview(SomeModelForm)), ``` -------------------------------- ### WizardView.get_form_kwargs Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Returns a dictionary of keyword arguments used for instantiating the form for a given step. Useful for passing custom arguments to form constructors. ```APIDOC ## WizardView.get_form_kwargs(step) ### Description Returns a dictionary which will be used as the keyword arguments when instantiating the form instance on given `step`. ### Method `get_form_kwargs(self, step)` ### Parameters #### Path Parameters - **step** (string) - Required - The current step in the wizard. ### Response #### Success Response (dict) - Returns a dictionary of keyword arguments for form instantiation. ``` -------------------------------- ### WizardView.process_step_files Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md A hook for post-processing form files before they are stored. Allows for additional actions or manipulation of file data associated with a form step. ```APIDOC ## WizardView.process_step_files(form) ### Description This method gives you a way to post-process the form files before the files gets stored within the storage backend. By default it just returns the `form.files` dictionary. You should not manipulate the data here but you can use it to do some extra work if needed (e.g. set storage extra data). ### Method `process_step_files(self, form)` ### Parameters #### Path Parameters - **form** (Form) - Required - The form instance containing the files. ### Response #### Success Response (dict) - Returns the processed form files dictionary. ``` -------------------------------- ### WizardView.process_step() Default Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Processes validated form data before it's stored. The default implementation returns the form's data dictionary. ```python def process_step(self, form): return self.get_form_step_data(form) ``` -------------------------------- ### Default WizardView get_form_step_data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Fetches and returns the data from a given form instance. Use this to manipulate values before they are stored. ```python def get_form_step_data(self, form): return form.data ``` -------------------------------- ### WizardView.get_form_step_files Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Returns the files associated with a form instance. This method allows manipulation of files before they are stored. ```APIDOC ## WizardView.get_form_step_files(form) ### Description Retrieves files from a form instance. Allows manipulation of files before storage. ### Method This method is part of the WizardView class. ### Parameters * **form** - The form instance from which to fetch files. ### Default implementation: ```python def get_form_step_files(self, form): return form.files ``` ``` -------------------------------- ### Display Form Fields for Preview Source: https://github.com/jazzband/django-formtools/blob/master/formtools/templates/formtools/preview.html Iterates through form fields to display their labels and data for review. This is typically used in a preview step. ```html {% for field in form %} {% endfor %} {{ field.label }}: {{ field.data }} ``` -------------------------------- ### WizardView.get_context_data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Generates the template context for a wizard step, including the form, wizard state, and any additional data. Allows for customization by adding extra variables. ```APIDOC ## WizardView.get_context_data(form, **kwargs) ### Description Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. The default template context variables are: * Any extra data the storage backend has stored * `wizard` – a dictionary representation of the wizard instance with the following key/values: * `form` – `Form` or `BaseFormSet` instance for the current step * `steps` – A helper object to access the various steps related data * `management_form` – all the management data for the current step ### Method `get_context_data(self, form, **kwargs)` ### Parameters #### Path Parameters - **form** (Form or BaseFormSet) - Required - The form instance for the current step. - **kwargs** - Optional - Additional keyword arguments. ### Response #### Success Response (dict) - Returns a dictionary containing the template context for the current step. ``` -------------------------------- ### WizardView.get_form_step_data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Fetches and returns the data from a given form instance. This method can be used to manipulate form values before they are stored. ```APIDOC ## WizardView.get_form_step_data(form) ### Description Retrieves data from a form instance. Allows manipulation of values before storage. ### Method This method is part of the WizardView class. ### Parameters * **form** - The form instance from which to fetch data. ### Default implementation: ```python def get_form_step_data(self, form): return form.data ``` ``` -------------------------------- ### WizardView.process_step Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md A hook for post-processing validated form data before it is stored. Allows for additional actions or data manipulation based on the cleaned form data. ```APIDOC ## WizardView.process_step(form) ### Description Hook for modifying the wizard’s internal state, given a fully validated `Form` object. The Form is guaranteed to have clean, valid data. This method gives you a way to post-process the form data before the data gets stored within the storage backend. By default it just returns the `form.data` dictionary. You should not manipulate the data here but you can use it to do some extra work if needed (e.g. set storage extra data). Note that this method is called every time a page is rendered for *all* submitted steps. ### Method `process_step(self, form)` ### Parameters #### Path Parameters - **form** (Form) - Required - The validated form instance for the current step. ### Response #### Success Response (dict) - Returns the processed form data dictionary. ``` -------------------------------- ### WizardView `done` method: Render validated data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This snippet shows a basic implementation of the `done` method that renders a template displaying the cleaned data from all validated forms. It's suitable for simple cases where no database operations are needed. ```python from django.shortcuts import render from formtools.wizard.views import SessionWizardView class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) ``` -------------------------------- ### WizardView.get_form_instance() Default Implementation Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Retrieves an instance object for a ModelForm from an internal dictionary. Returns None if no instance was provided. ```python def get_form_instance(self, step): return self.instance_dict.get(step, None) ``` -------------------------------- ### Wizard View with Condition Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Implements a SessionWizardView with a custom condition to conditionally display the second form based on user input from the first form. ```python from django.shortcuts import render from formtools.wizard.views import SessionWizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the field ``leave_message`` was checked. return cleaned_data.get('leave_message', True) class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) ``` -------------------------------- ### WizardView.get_form_instance Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Retrieves the model instance to be used when a ModelForm is employed for a specific step. Returns None if no instance was provided during wizard initialization. ```APIDOC ## WizardView.get_form_instance(step) ### Description This method will be called only if a `ModelForm` is used as the form for step `step`. Returns an `Model` object which will be passed as the `instance` argument when instantiating the `ModelForm` for step `step`. If no instance object was provided while initializing the form wizard, `None` will be returned. ### Method `get_form_instance(self, step)` ### Parameters #### Path Parameters - **step** (string) - Required - The current step in the wizard. ### Response #### Success Response (Model or None) - Returns a model instance or None. ``` -------------------------------- ### WizardView.get_cleaned_data_for_step Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Retrieves the cleaned data for a specific step, revalidating it through the form before returning. Returns None if data is invalid. ```APIDOC ## WizardView.get_cleaned_data_for_step(step) ### Description Fetches cleaned data for a given step after revalidation. Returns None if validation fails. ### Method This method is part of the WizardView class. ### Parameters * **step** - The identifier of the step for which to retrieve cleaned data. ``` -------------------------------- ### Render Form for Editing Source: https://github.com/jazzband/django-formtools/blob/master/formtools/templates/formtools/preview.html Renders the entire form using `as_table` for editing. Includes a CSRF token to ensure the form submission is secure. ```html {% csrf_token %} {{ form.as_table }} ``` -------------------------------- ### Run Specific Tox Environment Source: https://github.com/jazzband/django-formtools/blob/master/README.rst To execute tests for a particular environment, such as Python 3.10 with Django A.B.x, use the '-e' option followed by the environment name. ```bash $ tox -e py310-djangoAB ``` -------------------------------- ### WizardView.get_all_cleaned_data Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Returns a merged dictionary of all form steps' cleaned data. FormSet data is prefixed with 'formset-'. Later steps overwrite earlier steps with same field names. ```APIDOC ## WizardView.get_all_cleaned_data() ### Description Combines cleaned data from all wizard steps. Handles FormSet data and potential field name conflicts by prioritizing later steps. ``` -------------------------------- ### WizardView.file_storage Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Attribute to handle FileFields within wizard steps. Should be a Storage subclass for temporary file storage. ```APIDOC ## WizardView.file_storage ### Description An attribute that must be set to a Storage subclass to handle `FileField` uploads temporarily. Files are only removed if the wizard completes successfully. ### Example Implementation: ```python from django.conf import settings from django.core.files.storage import FileSystemStorage class CustomWizardView(WizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) ``` ### WARNING Ensure proper cleanup of temporary files, as `WizardView` only removes them upon successful wizard completion. ``` -------------------------------- ### Accessing form data by step name in `done` method Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This snippet illustrates how to access validated form data using the `form_dict` argument in the `done` method, which maps step names to their respective form instances. This is particularly useful with `NamedUrlWizardView`. ```python def done(self, form_list, form_dict, **kwargs): user = form_dict['user'].save() credit_card = form_dict['credit_card'].save() # ... ``` -------------------------------- ### Add 'formtools' to INSTALLED_APPS Source: https://github.com/jazzband/django-formtools/blob/master/docs/index.md Include 'formtools' in your Django project's INSTALLED_APPS setting. This is required for translations and templates to function correctly. ```python INSTALLED_APPS = ( # ... 'formtools', ) ``` -------------------------------- ### Include Security Hash and CSRF Token Source: https://github.com/jazzband/django-formtools/blob/master/formtools/templates/formtools/preview.html Includes a security hash for verification and a CSRF token for form security. This is essential for preventing cross-site request forgery. ```html {% blocktranslate %}Security hash: {{ hash_value }}{% endblocktranslate %} {% csrf_token %} {% for field in form %}{{ field.as_hidden }} {% endfor %} ``` -------------------------------- ### WizardView.render_revalidation_failure Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Handles the rendering when form revalidation fails after all steps are thought to be complete. It resets the current step to the failing form and renders it. ```APIDOC ## WizardView.render_revalidation_failure(step, form, **kwargs) ### Description Called when wizard forms fail revalidation after completion. Resets to the first failing step and renders the form. ### Method This method is part of the WizardView class. ### Parameters * **step** - The identifier of the failing step. * **form** - The form instance that failed validation. * **kwargs** - Additional keyword arguments. ### Default implementation: ```python def render_revalidation_failure(self, step, form, **kwargs): self.storage.current_step = step return self.render(form, **kwargs) ``` ``` -------------------------------- ### Define a FormPreview Subclass Source: https://github.com/jazzband/django-formtools/blob/master/docs/preview.md Override the done() method to process cleaned form data and return an HttpResponseRedirect. This method is called when the confirmation form is submitted from the preview page. ```python from django.http import HttpResponseRedirect from formtools.preview import FormPreview from myapp.models import SomeModel class SomeModelFormPreview(FormPreview): def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. return HttpResponseRedirect('/form/success') ``` -------------------------------- ### Define Wizard Forms Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md Defines two forms for a contact wizard. ContactForm1 includes basic fields and a checkbox, while ContactForm2 is for a message. ```python from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() leave_message = forms.BooleanField(required=False) class ContactForm2(forms.Form): message = forms.CharField(widget=forms.Textarea) ``` -------------------------------- ### Default WizardView render_revalidation_failure Source: https://github.com/jazzband/django-formtools/blob/master/docs/wizard.md This method is called when forms fail revalidation after all steps are thought to be complete. The default implementation resets the current step to the failing form and redirects the user. ```python def render_revalidation_failure(self, step, form, **kwargs): self.storage.current_step = step return self.render(form, **kwargs) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.