为 as_view() 添加额外上下文装饰器

2 投票
2 回答
1126 浏览
提问于 2025-04-17 19:14

我想从我的方法(视图)中调用一个基于类的通用视图,并且还想传递一些额外的上下文信息。可是我遇到了一个错误,提示是 as_view() 只接受一个参数(但我给了四个)。我正在使用 django-userena

执行这个的代码是:

return userena_views.ProfileListView.as_view(request,template_name='userena/profil.html', extra_context=projekti)

在 urls.py 文件中,我有这一行:

url(r'^accounts/(?P<username>[\.\w-]+)', userena_views.ProfileListView.as_view(template_name='userena/profil.html', extra_context=Projekat.objects.all), name='userena_profile_list'),

为什么这两者会不同呢?我哪里做错了?

2 个回答

1

基于类的视图可以通过一个叫做 get_context_data 的方法来提供额外的上下文数据。

下面这个例子来自于 Django 文档,在这个例子中,book_list 被添加到了 DetailView 的上下文中。这个方法在 FormViews 中也是可以使用的。

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

class PublisherDetailView(DetailView):

    model = Publisher

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

这是因为 url 函数的工作方式。你可以使用 kwargs 来传递参数,并且可以像下面这样定义一个网址模式:

url(r'^accounts/(?P<username>[\.\w-]+)', userena_views.ProfileListView.as_view(), name='userena_profile_list', kwargs={'template_name':'userena/profil.html', 'extra_context':Projekat.objects.all}),


编辑

我误解了你的问题,抱歉。现在,我来正确回答你的问题……你的代码应该是这样的:

your_callable_view = userena_views.ProfileListView.as_view()
return your_callable_view(request, template_name='userena/profil.html', extra_context=projekti)

原因是 ProfileListView.as_view() 返回一个需要用参数调用的函数。url() 会为你处理这个问题,这就是为什么它在你的网址模式中有效,而在你的代码中无效。as_view() 唯一需要的参数是 self

撰写回答