Django Form Wizard to Edit Model

前端 未结 5 535
攒了一身酷
攒了一身酷 2021-01-31 22:47

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 ex

5条回答
  •  灰色年华
    2021-01-31 23:32

    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[-\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.

提交回复
热议问题