如何在 django as_view() 方法中添加我自己的属性?

Posted

技术标签:

【中文标题】如何在 django as_view() 方法中添加我自己的属性?【英文标题】:How can i add my own attribute in django as_view() method? 【发布时间】:2020-05-13 18:31:39 【问题描述】:

我想在方法 'as_view()' 中添加我自己的属性 'fileName'

path('dialogs/', CodeResponseView.as_view(fileName='Dialogs.py')),

Django 给了我一个arror:

TypeError: CodeResponseView() received an invalid keyword 'fileName'. as_view only accepts arguments that are already attributes of the class.

【问题讨论】:

这能回答你的问题吗? Django class-based view: How do I pass additional parameters to the as_view method? CodeResponseView 是如何定义的?它继承自什么? 是的,对不起,我在那里找到了答案 ***.com/questions/11494483/… 。谢谢纳林 【参考方案1】:

你可以添加你的属性。你的情况 'filename' 在上下文中。

如果您想在模板端传递和使用,则使用 DetailViewListViewCreateView、TemplateView 等 通用类基础视图

有两种方法


1. 第一种方法是在 as_view 函数中传递参数,请参见此处不需要在视图端传递,或者如果您有模型,您也可以在 urls.py 中传递另一个关键字参数模型=

urls.py

path('dialogs/', CodeResponseView.as_view(extra_context='fileName':'Dialogs.py')),

然后您可以在模板端访问文件名属性,例如

您的模板文件

<h1> My file name is : filename </h1>

输出:

My file name is Dialogs.py


2. 第二种方法在您的视图类中分配 extra_context 字典,您在 view.py 文件中定义

urls.py

path('dialogs/', CodeResponseView.as_view()),

views.py 这里你不需要重写 get_context_data 方法来传递 filename

class CodeResponseView(DetailView):
    extra_context='filename':'Your File name'
    model=models.<model-name> # here your model name 

然后您可以在模板端访问文件名属性,例如

您的模板文件

&lt;h1&gt; My file name is : filename &lt;/h1&gt;

输出:

My file name is Your File name


在这里我放了一个额外上下文和预定义变量的 django 文档链接
    https://docs.djangoproject.com/en/3.0/ref/class-based-views/mixins-simple/

这些东西可以帮助你让我知道它的答案是对还是错.....

【讨论】:

【参考方案2】:

错误告诉你应该做什么:

as_view 只接受已经是类属性的参数

所以添加fileName 作为你的类的属性:

class CodeResponseView(View):
    fileName = ''

    # rest of view code can now use the fileName attribute

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['file'] = self.fileName
        return context

现在,任何将fileName 传递给as_view() 的url 模式都可以使用:

path('dialogs/', CodeResponseView.as_view(fileName='Dialogs.py')),
path('alerts/', CodeResponseView.as_view(fileName='Alerts.py')),

【讨论】:

我想为许多不同的文件使用一个视图类——我不想为许多文件使用许多视图类 你仍然可以这样做,我的代码显示fileName='',所以它是一个定义的属性,它只是将它初始化为空字符串,但你可以在as_view()方法中将它设置为你想要的任何值.现在在您的网址中,您可以执行.as_view(fileName="Dialogs.py"),在另一个网址中您可以执行.as_view(fileName="SomethingElse.py"),它会起作用。您不需要为每个文件名定义不同的类。 它工作!需要赋值,然后在def中作为“self.fileName”使用 它只能在 def.... 中工作。我输入“接受答案”并添加一些提交 :) 非常感谢,dirkgroten

以上是关于如何在 django as_view() 方法中添加我自己的属性?的主要内容,如果未能解决你的问题,请参考以下文章

Django:基于通用视图的“as_view()”方法

Django:“如何在将 url() 传递给 MyClass.as_view() 之前从 url() 获取 slug?”或“如何检查注册是不是开放?”

Django中的as_view方法源码分析

django的restformework模块的源码分析

django基类View.as_view()

Django drf:cbv(class base view)源码分析