在djangoTutorial的民意测验教程中,有什么方法可以将此FBV转换为CBV?

时间:2019-12-28 11:09:40

标签: django django-forms django-views

我尝试了一些尝试,但没有成功。我是初学者。

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,)))

2 个答案:

答案 0 :(得分: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,)))

答案 1 :(得分: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,)))