[Django]-Force django UpdateView to create an new object instead

5πŸ‘

βœ…

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)
πŸ‘€cms_mgr

1πŸ‘

Your solution (pk = None) definitely works (and is documented as a feature in the django doc – therefore it should wirk in the future as well), but if you want to do this manually, you can do the following:

In your form_valid(self, form), call a function create_new_triage(form.instance, self.request.user.person) whih does your job. form.incance holds the current instance of the model as entered by the user and you can use its values in a Triage.objects.create() method.

This gives you more control, but if you can do what you want with just setting pk = None, I would stick to that.

πŸ‘€OBu

Leave a comment