django形式的初始值

时间:2013-03-07 07:21:19

标签: django django-models django-forms django-views django-formwizard

Hello People这里是我的代码

class F1articles(forms.Form):
  heading=forms.CharField(max_length=100)
  content=forms.CharField(widget=forms.Textarea)
class F2articles(forms.Form):
  country=forms.CharField(max_length=100)
  work=forms.CharField(max_length=100)

这是在Urls.py中

url(r'^create/(?P<project_id>\d+)/$', FarticlesWizard.as_view([F1articles, F2articles]))

这是我的观点

class FarticlesWizard(SessionWizardView):
def done(self,form_list,**kwargs):
    form_dict={}
    Varticles_obj=None

    for x in form_list:
        form_dict=dict(form_dict.items()+x.cleaned_data.items())

    if kwargs.has_key('project_id'):
        Varticles_obj=Marticles.objects.get(id=kwargs['project_id'])
        Varticles_obj.heading=form_dict['heading']
        Varticles_obj.content=form_dict['content']
        Varticles_obj.country=form_dict['country']
        Varticles_obj.work=form_dict['work']
        Varticles_obj.modified_on=datetime.datetime.now()
        Varticles_obj.modified_by=self.request.user.username
        Varticles_obj.save()
        return HttpResponseRedirect('/display/')
    else:       
        insert_db=Marticles(heading = form_dict['heading'],
        content = form_dict['content'],
          country=form_dict['country'],work=form_dict['work'],created_by=self.request.user)
        insert_db.save()
        return HttpResponseRedirect('/display/')

这没有问题,但我想在调用网址时设置初始值以形成字段,有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以实施WizardView.get_form_initial(step)方法为向导的每个步骤提供初始数据。

类似的东西:

class FarticlesWizard(SessionWizardView):
    def get_form_initial(self, step):
        init_dict = {}
        #get object to populate data
        if step == '1':
            init_dict = { 'heading': obj.heading, 'content' : obj.content }
        if step == '2':
            init_dict = { 'country': obj.country, 'work' : obj.work }

        return init_dict

我不确定如何从url获取project_id来查询对象。

答案 1 :(得分:0)

嗯,我得到了它的工作,让我回答我自己的问题,...这是代码...

    def get_form_initial(self,step):

    if 'project_id' in self.kwargs:
        project_id=self.kwargs['project_id']
        article=Marticles.objects.get(id=project_id)
        project_dict = model_to_dict(article)
        return project_dict
    else:
        return self.initial_dict.get(step,{})

我认为这对你来说很有帮助......