我有一个自定义的基于类的视图
# 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参数(或其他参数)传递给视图
MyView.as_view(slug='hello_world')
我是否需要覆盖任何方法才能执行此操作?
答案 0 :(得分:104)
如果你的urlconf看起来像这样:
url(r'^(?P<slug>[a-zA-Z0-9-]+)/$', MyView.as_view(), name = 'my_named_view')
然后slug将在你的视图函数(例如'get_queryset')中可用,如下所示:
self.kwargs['slug']
答案 1 :(得分:80)
传递给as_view
方法的每个参数都是View类的实例变量。这意味着要添加slug
作为参数,您必须将其创建为子类中的实例变量:
# 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
答案 2 :(得分:17)
值得注意的是,您不需要覆盖get_object()
以便根据作为关键字arg传递的slug查找对象 - 您可以使用SingleObjectMixin
{{3的属性}}
# views.py
class MyView(DetailView):
model = MyModel
slug_field = 'slug_field_name'
slug_url_kwarg = 'model_slug'
context_object_name = 'my_model'
# urls.py
url(r'^(?P<model_slug>[\w-]+)/$', MyView.as_view(), name = 'my_named_view')
# mymodel_detail.html
{{ my_model.slug_field_name }}
(slug_field
和slug_url_kwarg
默认为'slug'
)
答案 3 :(得分:13)
如果要将对象添加到模板的上下文中,可以覆盖get_context_data
并添加到其上下文。如果您需要 request.user ,该请求也是 self 的一部分。
def get_context_data(self, **kwargs):
context = super(MyTemplateView, self).get_context_data(**kwargs)
if 'slug' in self.kwargs:
context['object'] = get_object_or_404(MyObject, slug=self.kwargs['slug'])
context['objects'] = get_objects_by_user(self.request.user)
return context
答案 4 :(得分:10)
您可以从urls.py传递参数 https://docs.djangoproject.com/en/1.7/topics/http/urls/#passing-extra-options-to-view-functions
这也适用于通用视图。例如:
url(r'^$', views.SectionView.as_view(), { 'pk': 'homepage', 'another_param':'?'}, name='main_page'),
在这种情况下,传递给视图的参数不一定是View类的实例变量。使用此方法,您不需要将默认页面名称硬编码到YourView模型中,但您可以将其作为urlconf中的参数传递。
答案 5 :(得分:7)
正如Yaroslav Nikitenko所述,如果您不想将新的实例变量硬编码到View类,则urls.py
可以pass extra options to view functions这样:
url(r'^$', YourView.as_view(), {'slug': 'hello_world'}, name='page_name')
我只是想在视图中添加如何使用它。您可以实现以下方法之一:
# If slug is optional
def the_function(self, request, slug=None):
# use slug here
# if slug is an optional param among others
def the_function(self, request, **kwargs):
slug = kwargs.get("slug", None)
other_param = kwargs.get("other_param", None)
# If slug is required
def the_function(self, request, slug):
# use slug here
答案 6 :(得分:3)
对于django 3.0,这对我有用:
# myapp/views.py
from django.views.generic import DetailView
class MyView(DetailView):
template_name = 'detail.html'
slug = None
def get_object(self, queryset=None):
self.slug = self.kwargs.get('slug', None)
return queryset.get(slug=self.slug)
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('slug/<slug:slug>/', views.MyView.as_view(), name='myview_by_tag'),
]