我在Ubuntu 14.04上使用python 2.7,Django 1.9.4。
我一直在与django-formtools(特别是形式向导)斗争了好几天了。方案如下:
表单向导只需两个步骤:
__init()__
需要一个参数(登录用户的id是一个整数)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")
我根据包括Stack Overflow在内的各种论坛中的建议覆盖了get_form_instance()
。 Information
是基于其创建AddPublisherForm
的Model类。
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)
然而,执行时,当我在Firefox中调用URL时,我收到错误__init__() takes at least 2 arguments (1 given)
。当我从forms.py中删除__init__()
时,代码运行正常。
关于如何在django-formtools中创建这个ModelForm的想法可以被集成。
答案 0 :(得分:0)
您需要覆盖get_form_kwargs
并添加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