Django Form Wizard to Edit Model

前端 未结 5 501
攒了一身酷
攒了一身酷 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:44

    pxg's answer is insufficient. As pointed out by emin-buğra-saral it creates a new instance of the model rather than editing it. And emin-buğra-saral's answer, by itself, isn't enough. Either don't override the get_form_initial method and don't set an initial_dict value or use the implementation provided in this answer. This is how you should combine their answers:

    in urls.py:

    (r'^projects/edit/(?P[-\d]+)$', ProjectWizard.as_view(FORMS)),

    in views.py:

    class ProjectWizard(SessionWizardView):
        def get_form_initial(self, step):
            if 'project_id' in self.kwargs:
                return {}
            return self.initial_dict.get(step, {})
    
        def get_form_instance(self, step):
            if not self.instance:
                if 'project_id' in self.kwargs:
                    project_id = self.kwargs['project_id']
                    self.instance = Project.objects.get(id=project_id)
                else:
                    self.instance = Project()
            return self.instance
    

    While pxg's version of get_form_initial would actually work (as long as you also add the get_form_instance override) it's not necessary to look up the instance, extract its data, and create an initial value dictionary. All this is done automatically by the ModelForm prior to initializing the instance from initial_dict. By simply returning an empty initial value dictionary you'll have simpler, more efficient code.

提交回复
热议问题