作为视图的函数知道问题,但是类却不知道(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,)))
答案 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
)或直接调用get
。 get(..)
函数将进行调用并传递**kwargs
参数。