Django Form Wizard to Edit Model
Answer a question
I have a Django form wizard working nicely for creating content of one of my models. I want to use the same Wizard for editing data of existing content but can't find a good example of how to do this.
Here is a simplified version of my project code:
forms.py
class ProjectEssentialsForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'title',
'short_description',
'who_description',
'problem_description',
'solution_description'
]
class ProjectYourInfoForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'gender',
'location',
'post_code',
'sector',
]
views.py
TEMPLATES = {
'project_essentials': 'projects/essentials-form.html',
'project_your_info': 'projects/your-info-form.html',
}
class ProjectWizard(SessionWizardView):
instance = None
def get_form_instance(self, step):
"""
Provides us with an instance of the Project Model to save on completion
"""
if self.instance is None:
self.instance = Project()
return self.instance
def done(self, form_list, **kwargs):
"""
Save info to the DB
"""
project = self.instance
project.save()
def get_template_names(self):
"""
Custom templates for the different steps
"""
return [TEMPLATES[self.steps.current]]
urls.py
FORMS = [
('project_essentials', ProjectEssentialsForm),
('project_your_info', ProjectYourInfoForm),
]
urlpatterns = patterns('',
(r'^projects/add$', ProjectWizard.as_view(FORMS)),
)
I see that there is this function https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/#django.contrib.formtools.wizard.views.WizardView.get_form_instance for setting the form instance, but I'm not sure how you would go about getting the models ID to do the look-up here and exactly how the code would work.
A code example or a link to one would be most appreciated.
Thanks, Pete
Answers
I've just got this working so will post the answer in case it helps someone else.
You can pass the ID of the item you'd like to edit in urls.py like this:
(r'^projects/edit/(?P<project_id>[-\d]+)$', ProjectWizard.as_view(FORMS)),
You can then look up the item with following code in
views.py:
class ProjectWizard(SessionWizardView):
def get_form_initial(self, step):
if 'project_id' in self.kwargs and step == 'project_essentials':
project_id = self.kwargs['project_id']
project = Project.objects.get(id=project_id)
from django.forms.models import model_to_dict
project_dict = model_to_dict(project)
return project_dict
else:
return self.initial_dict.get(step, {})
You need to convert the model to a dict so you can set it as the initial data.
更多推荐

所有评论(0)