Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force django UpdateView to create an new object instead

Tags:

django

I have a model that will be updated throughout its lifetime. I want each update to return a new object based on the old one, rather than update the original. This is to give users the previous object as a reference while ensuring they don't overwrite it. I tried using the same form, which this question suggested might accomplish what I wanted but it didn't (it updated instead). Then I tried overriding the save method to point to my CreateView as in the code below but that told me it needed a CreateView instance as its first argument. Is there a way to get the behaviour I want?

class TriageUpdateView(PermissionRequiredMixin, UpdateView):
    model = Triage
    form_class = TriageForm
    login_url = "/login/"
    permission_required = "myapp.add_triage"

    def form_valid(self, form):
        obj = form.save(commit = False)
        obj.completed_by = self.request.user.person
        return TriageCreateView.form_valid(self, form)
like image 905
cms_mgr Avatar asked Dec 10 '25 23:12

cms_mgr


1 Answers

I've found a way, though I'm not sure it's the best way. Django decides whether to update or insert in the database by checking for a primary key value. I set this to None in the validation and that's done the trick.

class TriageUpdateView(PermissionRequiredMixin, UpdateView):
    model = Triage
    form_class = TriageForm
    login_url = "/login/"
    permission_required = "myapp.add_triage"

    def form_valid(self, form):
        obj = form.save(commit = False)
        obj.pk = None
        obj.completed_by = self.request.user.person
        return super(TriageUpdateView, self).form_valid(form)
like image 159
cms_mgr Avatar answered Dec 12 '25 13:12

cms_mgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!