Django 基于类的视图:如何将附加参数传递给 as_view 方法?
我有一个自定义的基于类的视图
I have a custom class-based view
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
我想像这样传入 slug 参数(或其他参数给视图)
I want to pass in the slug parameter (or other parameters to the view) like this
MyView.as_view(slug='hello_world')
我是否需要覆盖任何方法才能做到这一点?
Do I need to override any methods to be able to do this?
传递给 as_view
方法的每个参数都是 View 类的实例变量.这意味着将 slug
添加为参数,您必须在子类中将其创建为实例变量:
Every parameter that's passed to the as_view
method is an instance variable of the View class. That means to add slug
as a parameter you have to create it as an instance variable in your sub-class:
# myapp/views.py
from django.views.generic import DetailView
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
# additional parameters
slug = None
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
这应该能让 MyView.as_view(slug='hello_world')
工作.
如果您通过关键字传递变量,请使用 Erikkson 先生的建议:https://stackoverflow.com/a/11494666/9903
If you're passing the variables through keywords, use what Mr Erikkson suggested: https://stackoverflow.com/a/11494666/9903