I am rewriting a big piece of our application which requires a user to create a Project
with Rewards
attached to it.
The form is broken into different steps, the first two are the normal Project
, the next one is the Rewards
, and then lastly a simple preview that lets the user flick back and forth to create a perfect Project
.
my forms.py
class BaseRewardFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseRewardFormSet, self).__init__(*args, **kwargs)
self.queryset = Reward.objects.none()
RewardFormSet1 = modelformset_factory(Reward, extra=2, exclude=('project'), formset=BaseRewardFormSet)
class ProjectForm1(forms.ModelForm):
"""docstring for ProjectForm1"""
class Meta:
model = Project
exclude=( ... )
class ProjectForm2(forms.ModelForm):
"""docstring for ProjectForm2"""
class Meta:
model = Project
exclude = ( ... )
my urls.py
instance_dict = {'2': Reward.objects.none()}
url(r'^new-project/$', login_required(ProjectWizard.as_view([ProjectForm1, ProjectForm2, RewardFormSet1, ProjectForm3], instance_dict=instance_dict))),
my views.py
class ProjectWizard(SessionWizardView):
file_storage = cloudfiles_storage
def get_context_data(self, form, **kwargs):
context = super(ProjectWizard, self).get_context_data(form, **kwargs)
initial_dict = self.get_form_initial('0')
if self.steps.current == '1':
step1_data = self.get_cleaned_data_for_step('0')
context.update({'step1_data':step1_data,'currency_sign':step1_data['base_currency']})
else:
step1_data = self.get_cleaned_data_for_step('0')
step2_data = self.get_cleaned_data_for_step('1')
step3_data = self.get_cleaned_data_for_step('2')
context.update({'step1_data':step1_data,'step2_data':step2_data,'step3_data':step3_data,})
return context
def get_template_names(self):
step = int(self.steps.current)
if step == 3:
return 'formwizard/preview.html'
else:
return 'formwizard/wizard_form.html'
def done(self, form_list, *args, **kwargs):
form_data = form_list[0].cleaned_data
form_data_details = form_list[1].cleaned_data
form_data.update(form_data_details)
project = Project()
for field in project.__dict__.iterkeys():
if field in form_data:
project.__dict__[field] = form_data[field]
project.owner = self.request.user
project.date_published = datetime.now()
project.save()
return render_to_response('formwizard/done.html', {
'form_data': [form.cleaned_data for form in form_list],
})
when rendering redirect, it shows that all the data has been cleaned which means that the form is valid, and all the project data is saved to Project
I can see that the Rewards data will not save since it has not been called, but every solution I have tried thus far has failed.
How can I implement Rewards into this solution on save?
Maybe someone can shed some light on this, much appreciated!
Is this working? Assuming Reward
has project
.
for rw in form_list[2].save(commit=False):
rw.project = project
rw.save()
来源:https://stackoverflow.com/questions/11612603/django-formwizard-and-modelformset-save