Django Class Based View for both Create and Update

后端 未结 7 847
有刺的猬
有刺的猬 2020-12-13 18:46

Say I want to create a Class Based View which both updates and creates an object. From a previous question I worked out I

7条回答
  •  情深已故
    2020-12-13 19:30

    Simplest and basically the best solution of all link

    class WorkerUpdate(UpdateView):
        form_class = WorkerForm
    
        def get_object(self, queryset=None):
    
            # get the existing object or created a new one
            obj, created = Worker.objects.get_or_create(mac=self.kwargs['mac'])
    
            return obj
    

    and that's it thanks @chriskief

提交回复
热议问题