[Answer]-CreateOrUpdateView for Django Models

1👍

The UpdateView and CreateView are really not that different, the only difference is that UpdateView sets self.object to self.get_object() and CreateView sets it to None.

The easiest way would be to subclass UpdateView and override get_object():

AnswerQuestionView(LoginRequiredMixin, UpdateView):
    def get_object(queryset=None):
        if queryset is None:
            queryset = self.get_queryset()

        # easy way to get the right question from the url parameters:
        question = super(AnswerQuestionView, self).get_object(Question.objects.all())

        try:
            obj = queryset.get(user=self.request.user, question=question)
        except ObjectDoesNotExist:
            obj = None
        return obj

Returns the right answer if it exists, None if it does not. Of course add any attributes you need to the class, like model, form_class etc.

👤knbk

Leave a comment