我在Django和Django Rest Framework中编写我的第一个应用程序。现在我被困在一个创建视图上。该视图必须为用户创建一个新项目。
这是我的模特:
from django.db import models
from django.contrib.auth.models import User
class Projects(models.Model):
"""Model containing all the project information."""
NEW = 'NEW'
PENDING = 'PENDING'
OPEN = 'OPEN'
ACTIVE = 'ACTIVE'
CLOSED = 'CLOSED'
DELIVERED = 'DELIVERED'
PROJECT_STATUS_CHOICES = (
(NEW, 'New'),
(PENDING, 'Pending'),
(OPEN, 'Open'),
(ACTIVE, 'Active'),
(CLOSED, 'Closed'),
(DELIVERED, 'Delivered'),
)
project_owner = models.ForeignKey(User, related_name='project_owner')
project_number = models.CharField(max_length=50, unique=True)
date = models.DateField(blank=True)
title = models.CharField(max_length=50)
status = models.CharField(max_length=15,
choices=PROJECT_STATUS_CHOICES,
default=NEW)
slug = models.SlugField(max_length=50, unique=True)
summary = models.TextField()
def __unicode__(self):
return self.project_number
这是项目的视图。列表和检索功能有效。问题在于如下所示的创建视图:
from django.contrib.auth.models import User
from rest_framework import viewsets, status
from rest_framework.response import Response
from userpermissions.views import PhotographerPermission
from projects.models import Projects
from projects.serializers import ProjectSerializer
class ProjectView(viewsets.ViewSet):
model = Projects
serializer_class = ProjectSerializer
permission_classes = (PhotographerPermission,)
def get_serializer_context(self):
return {'request': self.request}
def list(self, request):
user = request.user
queryset = Projects.objects.filter(project_owner=user)
serializer = ProjectSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, project_id=None):
user = request.user
queryset = Projects.objects.filter(project_owner=user, id=project_id)
serializer = ProjectSerializer(queryset, many=True)
return Response(serializer.data)
def create(self, request):
serializer = ProjectSerializer(data=request.data, many=True)
user = User.objects.get(username=request.user)
if serializer.is_valid():
serializer.project_owner = user.id
serializer.save()
return Response({'status': 'done'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
每当我尝试创建项目时,函数都会返回'done'。所以我认为它已经执行并保存了一个新项目。但是该项目不在数据库中。我无能为力,而且我似乎没有在互联网上找到各种修复工作。
这里是参考序列化器代码:
from rest_framework import serializers
from projects.models import Projects
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Projects
fields = ('project_number', 'date', 'title', 'status', 'slug', 'summary')
extra_kwargs = {
'project_owner': {'write_only': True}
}
def create(self, validated_data):
"""
Create and return a new 'Project'.
"""
return Projects.objects.create(**validated_data)