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 *
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')
work。
如果您通过关键字传递变量,请使用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