Django基于类的视图:如何传递其他参数到as_view方法? [英] Django class-based view: How do I pass additional parameters to the as_view method?

查看:1924
本文介绍了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

这篇关于Django基于类的视图:如何传递其他参数到as_view方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆