【问题标题】:How can i add my own attribute in django as_view() method?如何在 django as_view() 方法中添加我自己的属性?
【发布时间】: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


【解决方案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


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

【讨论】:

    【解决方案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
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多