【问题标题】:Using custom class view in django get me error在 django 中使用自定义类视图让我出错
【发布时间】:2019-03-23 09:48:40
【问题描述】:

我正在学习 django,我正在尝试在 views.py 文件中创建自己的自定义类

这个类我会使用 has to 方法,一个用于经典的 HTML 渲染,另一个用于 json 响应

views.py 中我的类

class myListView():
    context = {}
    def __init__(self, request):
        request = request
        context['PageTitle'] = 'Contacts'
        context['people'] = People.objects.all()

    def htmlRender(self, *args, **kwargs):
        context['children_template'] = 'people/list.html'
        return render(request,'base.html',context)

    def jsonRender(self, *args, **kwargs):
        return HttpResponse(json.dumps(self.context['people']), content_type="application/json")

我的 urls.py

    path('list', login_required(myListView.htmlRender()), name='list'),
    path('list/json', login_required(myListView.jsonRender()), name='list'),

这是调试器发送的错误:

TypeError: htmlRender() missing 1 required positional argument: 'self'

我不知道如何解决这个问题,也许我梦想在视图中使用自定义类?

谢谢你

【问题讨论】:

  • myListView().htmlRender() 怎么样?
  • 如果我在 urls 中写这个,那就是响应 TypeError: __init__() missing 1 required positional argument: 'request'

标签: python django class view


【解决方案1】:
from django.views.generic import ListView

class myListView(ListView):

也许你没有扩展 ListView 类,试试这个。

【讨论】:

    【解决方案2】:

    您应该首先从“myListView”类创建一个实例,然后使用它:

    myListViewInstance = myListView(arguments)
    
    myListViewInstance.htmlRender()
    

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多