Search code examples
pythondjangopython-2.7django-formwizard

Form wizard with ModelForms having parameters in __init__


I am using python 2.7, Django 1.9.4 on Ubuntu 14.04.

I have been struggling with django-formtools (specifically form wizard) for quite a few days now. The scenario is as follows:

The form wizard is just a 2 step process:

  1. 1st step: I have a ModelForm based on a Model. The form's __init()__ requires a parameter (the id of logged in user which is an integer)
  2. 2nd step: A simple check box that asks user of he/she wants to submit the form.

The source for forms.py:

from django import forms
from publishermanagement import models
from localemanagement import models as locale_models
from usermanagement import models as user_models


class AddPublisherForm(forms.ModelForm):
def __init__(self, user_id, *args, **kwargs):
    super(AddPublisherForm, self).__init__(*args, **kwargs)
    permitted_locale_ids = (
        user_models
        .PublisherPermission
        .objects
        .filter(user=user_id)
        .values_list('locale', flat=True))
    self.fields['locale'].queryset = (
        locale_models
        .Locale
        .objects
        .filter(pk__in=permitted_locale_ids))

class Meta:
    model = models.Information
    fields = (
        'channel_type',
        'current_deal_type',
        'locale',
        'name',
        'contact_primary',
        'contact_auxiliary',
        'website',
        'phone',
        'is_active',)


class ConfirmPublisherForm(forms.Form):
confirmation = forms.BooleanField(
    label="Check to confirm provided publisher data")

I overwrote the get_form_instance() in line with the suggestions in various forums including Stack Overflow. Information is the Model class based on which AddPublisherForm is created.

views.py

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from publishermanagement import models as publisher_models
from formtools.wizard.views import SessionWizardView

class CreatePublisherWizard(SessionWizardView):

@login_required(login_url='/account/login/')
def done(self, form_list, **kwargs):
    # code for saving form data to be done here if user confirms the data
    # else redirect to the main form.
    return render_to_response(
        'publishermanagement/wiz.html',
        {'form_data': [form.cleaned_data for form in form_list]})

def get_form_instance(self, step):
    if step == u'0':

        info = publisher_models.Information()
        return info
    # the default implementation
    return self.instance_dict.get(step, None)

However, upon execution, when I call the URL in Firefox, I am getting the error __init__() takes at least 2 arguments (1 given). When I remove the __init__() from my forms.py, the code runs fine.

And ideas on how can create this ModelForm in django-formtools be integrated.

Some relevant post: Access Request Object in WizardView Sublcass


Solution

  • You need to override get_form_kwargs and include the user_id.

    class CreatePublisherWizard(SessionWizardView):
        ...
        def get_form_kwargs(self, step):
            kwargs = super(CreatePublisherWizard, self).get_form_kwargs(step)
            if step == u'0':
                kwargs['user_id'] = self.request.user.id
            return kwargs