我是django的新手。我正在尝试构建一个应用程序。但问题是,当我尝试启动服务器时,仍然在views.py中定义了函数,它说“模块”对象没有属性。
股票/ urls.py
from django.conf.urls import url
from stock import views
urlpatterns = [
url(r'^stocks/$', views.stock_list),
url(r'^stocks/(?P<pk>[0-9]+)/$', views.stock_detail),
]
股票/ views.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from stock.models import Stock
from stock.serializers import StockSerializer
class JSONResponse(HttpResponse):
# An HttpResponse that renders its content into JSON.
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def stock_list(request):
# List all code snippets, or create a new snippet.
if request.method == 'GET':
stocks = Stock.objects.all()
serializer = StockSerializer(stock, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = StockSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
@csrf_exempt
def stock_detail(request, pk):
# Retrieve, update or delete a code snippet.
try:
stock = Stock.objects.get(pk=pk)
except Stock.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = StockSerializer(stock)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = StockSerializer(stock, data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
Stock.delete()
return HttpResponse(status=204)
我收到了以下错误
File "/users /ha/code/RiskAdvisor/riskadvisor/stock/urls.py", line 5, in <module>
url(r'^stocks/$', views.stock_list),
AttributeError: 'module' object has no attribute 'stock_list'
答案 0 :(得分:0)
正如所写,stock_list
是JSONResponse
类中的一种方法(request
应该是JSONResponse
类型,通常称为self
)。显然,这不是你的意思。它应该是一个简单的模块级功能。简单地说一次。
class JSONResponse(HttpResponse):
# An HttpResponse that renders its content into JSON.
def __init__(self, data, **kwargs):
...
@csrf_exempt
def stock_list(request):
...
我使用的IDE PyDev表示您的代码出错:
方法stock_list应该将self作为第一个参数
它还告诉我serializer = StockSerializer(stock, many=True)
包含一个拼写错误 - 那里没有stock
变量。你可能意味着stocks
?
使用一个好的IDE。