当前位置: 动力学知识库 > 问答 > 编程问答 >

Initial values in django forms

问题描述:

Hello People here is my code

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)

this is in Urls.py

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

this is my view

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/')

this works fine with no issues but i want to set initial values to form fields when the url is called,, is there a way to fix this?

网友答案:

You can implement WizardView.get_form_initial(step) method to provide initial data for each step of the wizard.

Something like:

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

I'm not sure how would you get project_id in this method from url to query the object.

网友答案:

hmmm i got it working,Let me answer my own question,..here is the code ...

    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,{})

I think this will be helpfull for you guyzz...

分享给朋友:
您可能感兴趣的文章:
随机阅读: