gpt4 book ai didi

Django 泛型基于类的 View 示例 : where does **kwargs come from?

转载 作者:行者123 更新时间:2023-12-04 11:13:46 25 4
gpt4 key购买 nike

在示例中,我经常看到 **kwargs 传递,但没有提及它来自哪里:

from django.views.generic import DetailView
from books.models import Publisher, Book

class PublisherDetailView(DetailView):

context_object_name = "publisher"
model = Publisher

def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherDetailView, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context

**kwargs 是从哪里神奇地拔出来的?

另外,这似乎不是为了添加一个字典对象而做的大量额外工作吗?

最佳答案

查看 SingleObjectMixin 的基本实现(“原始”get_context_data)。

它只是返回 **kwargs作为上下文(字典),同时添加使用指定键编辑的对象。

 def get_context_data(self, **kwargs):
context = kwargs
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
return context

DetailView ,这些 kwargs 是从任何叫它的东西中“神奇地拔出”/传入这些 kwargs 的。在您的情况下,这将是 BaseDetailView.get() .
class BaseDetailView(SingleObjectMixin, View):
def get(self, request, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)

它后来被许多 View 类(如 render_to_response(self.get_context_data) )使用,它们通过原始 context字典到 self.response_class默认为 django.template.TemplateResponse .
TemplateResponse知道如何渲染自己,并且在其 resolve_context函数,最后将字典转换为 django.template.Context
你真的可以从原始方法一直到源头。

关于Django 泛型基于类的 View 示例 : where does **kwargs come from?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7911858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com