我在一个项目中使用Django Rest Framework。我在序列化器字段中设置了所有Group模型属性,因此当我发出GET请求时,我会收到所有数据。好。但是当一些用户想要创建一个组(POST方法)时,一旦我在请求中获得用户ID,这就成了一个麻烦 - 什么会产生错误的请求。
我的模特:
class Group(models.Model):
class Meta:
app_label = 'base'
PRIVACY = Choices(
('0', u'Público'),
('1', 'Particular'),
('2', 'Secreto'),
)
name = models.CharField(max_length=62, unique=False)
privacy = models.CharField(max_length=2, choices=PRIVACY)
end_date = models.DateTimeField(auto_now_add=True, editable=False)
date_created = models.DateTimeField(auto_now_add=True, editable=False)
admin = models.ForeignKey(User, related_name='admin')
member = models.ManyToManyField(User, through='Membership')
我的序列化器:
class GroupSerializer(serializers.ModelSerializer):
# admin = serializers.CharField(source='admin.id')
class Meta:
model = Group
fields = ('name', 'privacy', 'status', 'end_date', 'date_created', 'admin')
我的观点:
class GroupList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
"""
List all groups, or create a new group.
"""
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
queryset = Group.objects.all()
serializer_class = GroupSerializer
def perform_create(self, serializer):
serializer.save(admin=self.request.user)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
更新请求例如:
var data = {
'name': 'New name',
'privacy': '0',
'end_date':'2015-12-22 19:53:42',
};
$.ajax({
url: '/groups/',
method: 'POST',
data:data
}).done(function(response) {
console.log(response);
});
错误:
{"admin":["This field is required."]}