0

我已经尝试了一些东西,但没有得到它的工作。我是初学者。

def vote(request, question_id):

    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
4

2 回答 2

1

有很多方法可以将此 FBV 转换为 CBV。最基本的一个是您只需将相同的逻辑复制粘贴到基于类的视图的getpost函数中,它就可以正常工作。

from django.views import View

class PollDetailsView(View):
    def get(self, request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
于 2019-12-28T11:39:28.983 回答
0

我已将 FBV 转换为 CBV 以用于投票应用程序。那么现在有人可以指导我如何使用这些表单视图方法而不是简单的获取和发布吗? https://ccbv.co.uk/projects/Django/2.2/django.views.generic.edit/FormView/

我的项目:https ://github.com/moaazafzal/Polls-Django

类 DetailFormClass(generic.View): template_name = "polls/details.html"

def get(self, request, *args, **kwargs):
    myquestion = Question.objects.get(id=kwargs['pk'])
    # choice_form = ChoiceForm()
    # question_form=QuestionForm()
    #
    #
    context = {"question" : myquestion}
    return render(request, self.template_name,context)

def post(self, request, *args, **kwargs):
    question = get_object_or_404(Question, id=kwargs['pk'])
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
于 2020-01-08T07:12:21.067 回答