serializers.py:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("mcc.xml");
if (is == null) {
// file not found or something went wrong
}
// read the stream
view.py:
class SnippetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Snippet
fields = ('id', 'title','owner', 'code', 'linenos', 'language', 'style')
def create(self, validated_data):
owner=validated_data.pop('owner')
try:
owner=User.objects.get(username=owner)
snippet=Snippet.objects.create(owner=owner,**validated_data)
return snippet
except:
return Http404
型号:
class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
data=request.data
data['owner']=request.user
serializer = SnippetSerializer(data=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)
发布数据:
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
owner = models.ForeignKey(User)
highlighted = models.TextField()
错误:/ snippets /'所有者'
中的KeyError