我正在尝试运行一个使用django rest framework的应用程序。但是我收到导入错误"无法导入名称DurationField"。如何解决此错误?
错误讯息 enter image description here
Views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from restapp.serializers import UserSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class UserList(APIView):
#List all user,create new one
def get(self,request,format=None):
users = User.objects.all()
serializer = UserSerializer(users,many=True)
return Response(serializer.data)
def post(self,request,format=None):
serializer= UserSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,pk, format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class UserDetail(APIView):
#Retrive update,or delete a user instance
def get_object(self,pk):
try:
return User.objects.get(pk=pk)
except user.DoesNotExist:
raise 404
def get(self,request,pk,format=None):
user = self.get_object(pk)
user = UserSerializer(user)
return Response(user.data)
def put(self,request,pk,format=None):
user = self.get_object(pk)
serializer=UserSerializer(user,data = request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,pk,format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','firstname','last_name','email')
它指向此文件serializers.py,第18行作为错误源。
答案 0 :(得分:5)
从屏幕截图中,我可以看到您正在使用Django 1.7。
DRF导入的DurationField
是在Django 1.8中引入的。
所以你必须升级你的Django才能使这个版本的DRF正常工作。