TypeError: __init__() takes 1 positional argument but 2 were given

来源:5-2 django的view实现商品列表页

iceps

2020-03-31

老师,我这里view中使用函数的话一切正常,使用类就报“TypeError: init() takes 1 positional argument but 2 were given”这个错误

使用函数代码如下

import json
from django.http import HttpResponse
from goods.models import Goods

def GoodsListView(request):

    json_list = []
    goods = Goods.objects.all()[:10]
    for good in goods:
        json_dict = {}
        json_dict["name"] = good.name
        json_dict["market_price"] = good.shop_price
        json_list.append(json_dict)
    return HttpResponse(json.dumps(json_list),content_type="application/json")

使用类代码如下

import json
from django.http import HttpResponse
from goods.models import Goods
from django.views import View
class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]
        for good in goods:
            json_dict = {}
            json_dict["name"] = good.name
            json_dict["market_price"] = good.shop_price
            # json_dict["add_time"] = good.add_time
            json_list.append(json_dict)
        return HttpResponse(json.dumps(json_list),content_type="application/json")
即使把django.views.View改成django.views.generic.base.View还是一样报错
from django.views.generic.base import View

错误提示如下

?图片描述
不知道是什么问题?

写回答

1回答

bobby

2020-03-31

0
2
bobby
回复
iceps
两者是一样的 都能直接返回json你先修改一下试试有没有报错
2020-04-01
共2条回复

Python前后端分离开发Vue+Django REST framework实战

Django REST framework课程视频,RESTFul API前后端分离开发

2873 学习 · 2457 问题

查看课程