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

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

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

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