[Answered ]-Which classes should I use to modify an object without a form and UpdateView involved using Django?

2πŸ‘

βœ…

I disagree with your approach of not using a FormView. The confirmation actually is a Form (even if it does only have a Confirm button) β€” not a ModelForm but a normal django form that confirms your selection.

What I propose doing instead is inherit from FormView and also add a SingleObjectMixin. Something like this (this is from a Cancel method I’d implemented in a different project but you’ll get the idea):

class CancelFormView(FormView, SingleObjectMixin):
    queryset = models.Process.all()
    form_class = forms.YesNoForm
    template_name = 'cancel.html'

    def form_valid(self, form):
        obj = self.get_object()
        yesno = form.cleaned_data['yesno']
        if yesno=='YES':
            # Do something with the object
            # the update_fields method you define should be a method of your object
            obj.cancel()
            messages.info(self.request, u"Cancel ok!")
        else:
            messages.info(self.request, u"Cancel aborted!")
        return HttpResponseRedirect(reverse("process_view", args=[obj.id] ))

As you see, you just need to override the form_valid method of your Class and define the queryset, form_class and template_name attributes. You then just update your fields (or do whatever else you like) if the user has actually confirmed that he wants it (he has selected β€˜YES’ in the form). I believe that this is the most DRY way of implementing your requirements.

πŸ‘€Serafeim

Leave a comment