Django-formwizard和ModelFormSet保存 [英] Django-formwizard and ModelFormSet save

查看:138
本文介绍了Django-formwizard和ModelFormSet保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写我们的一个应用程序,需要用户创建一个项目奖励附加到



表单分为不同的步骤,前两个是正常的 Project ,下一个是奖励,然后最后一个简单的预览,让用户来回轻松创建一个完美的项目。 / p>

我的forms.py

  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 =(...)

我的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)),

我的views.py

 类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()
为项目中的字段。_ dict __。iterkeys():
如果form_data中的字段:
project .__ dict __ [field] = form_data [field]
project.owner = self.request.user
project.date_published = datetime.now()
project.save()
返回render_to_response('formwizard / done.html',{
'form_data':form_list中的表单的form.cleaned_data],
})

当渲染重定向时,它显示所有数据已被清除,这意味着表单有效,并且所有项目数据保存到项目



我可以看到,奖励数据不会保存,因为它没有被调用,但是我尝试过的每个解决方案远远失败了。



如何在保存中实施奖励?



可能有人可以在这一点上解释一下,非常感谢!

解决方案

这是否正常?假设奖励项目

 code> for form_list [2] .save(commit = False)
rw.project = project
rw.save()
/ pre>

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()

这篇关于Django-formwizard和ModelFormSet保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆