我正在尝试用django实现简单的rest api。但是我收到以下错误,
// model.py
from django.db import models
# Create your models here.
class Event(models.Model):
name = models.TextField()
type = models.TextField()
location = models.TextField()
start_hour = models.TextField()
end_hour = models.TextField()
creator = models.TextField()
class Meta:
verbose_name = "Event"
verbose_name_plural = "Events"
def __str__(self):
return self.name
// serializer.py
from rest_framework import serializers
from .models import Event
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('name', 'type')
// urls.py
from django.conf.urls import url
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from events import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^events/', views.EventList.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
我对django太新了,我无法弄清楚如何处理这个错误。请帮帮我们。
答案 0 :(得分:0)
这个设置没有任何问题,从教程中删除。
项目文件夹events
。
应用程序文件夹django_example/settings.py
。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'events.apps.EventsConfig'
]
添加:
events/apps.py
添加:
from __future__ import unicode_literals
from django.apps import AppConfig
class EventsConfig(AppConfig):
name = 'events'
events/models.py
对于上下文,from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Event(models.Model):
name = models.TextField()
kind = models.TextField()
location = models.TextField()
start_hour = models.TextField()
end_hour = models.TextField()
creator = models.TextField()
class Meta:
verbose_name = "Event"
verbose_name_plural = "Events"
def __str__(self):
return self.name
看起来像这样:
type
请勿使用events/serializers.py
作为字段名称。
添加:
from rest_framework import serializers
from .models import Event
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('name', 'kind')
events/views.py
from django.shortcuts import render
# Create your views here.
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 events.models import Event
from events.serializers import EventSerializer
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 event_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Event.objects.all()
serializer = EventSerializer(snippets, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = EventSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
@csrf_exempt
def event_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
event = Event.objects.get(pk=pk)
except event.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = EventSerializer(snippet)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = EventSerializer(event, data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
event.delete()
return HttpResponse(status=204)
添加:
events/urls.py
from django.conf.urls import url
from events import views
urlpatterns = [
url(r'^events/$', views.event_list),
url(r'^events/(?P<pk>[0-9]+)/$', views.event_detail),
]
添加:
django_example/urls.py
添加:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('events.urls'))
]
int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be < =_dict.Count - 1
如果您在填充models.py后运行迁移,则应该能够看到API的响应,即使它只是一个空列表。