Dfango函数视图VS类RedirectView。如何使类视图接受参数

时间:2018-09-01 22:02:54

标签: python django generics view

作为视图的函数知道问题,但是类却不知道(args,kwargs来自url,空,post方法只有选择,而不是问题)。 两者都可以,但是要添加支票,我想知道如何在课堂上提问。它的init或get_redirect_url或请求中没有问题,如question_id

url.py

from django.urls import path
from . import views
app_name = 'polls'
ulrpatterns=[
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('<int:pk>/vote0/', views.vote0.as_view(), name='vote0'),
]

views.py

class vote0(generic.base.RedirectView):
    pattern_name = 'polls:results'
    def get_redirect_url(self, *args, **kwargs):
        selected_choice = get_object_or_404(Choice, pk(self.request.POST['choice']))
        selected_choice.votes +=1
        selected_choice.save()
        return super().get_redirect_url(*args, **kwargs)


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
    selected_choice.votes += 1
    return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

1 个答案:

答案 0 :(得分:1)

get_redirect_url带有 named URL参数(**kwargs),因此您可以重写签名以捕获这些签名。例如:

class vote0(generic.base.RedirectView):
    pattern_name = 'polls:results'

    def get_redirect_url(self, *args, question_id=None, **kwargs):
        question = get_object_or_404(Question, pk=question_id)
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
        selected_choice.votes +=1
        selected_choice.save()
        return super().get_redirect_url(*args, **kwargs)

或者您也可以在self.args中访问 positional URL参数,并在self.kwargs中访问 named URL参数。

背景

如果我们看一下"derived"的实现,就会发现如果我们将RedirectView构造成一个普通视图,它将看起来像:

class RedirectView(View):

    # ...

    def get(self, request, *args, **kwargs):
        url = self.get_redirect_url(**kwargs)
        if url:
            if self.permanent:
                return http.HttpResponsePermanentRedirect(url)
            else:
                return http.HttpResponseRedirect(url)
        else:
            logger.warning('Gone: %s', self.request.path,
                        extra={
                            'status_code': 410,
                            'request': self.request
                        })
            return http.HttpResponseGone()

    def post(self, request, *args, **kwargs):
        return self.get(request, *args, **kwargs)

因此,调度程序将调用post(仅包装get)或直接调用getget(..)函数将进行调用并传递**kwargs参数。