我正在关注身份验证的django REST框架教程。权限。根据教程,我定义了模型和视图,我收到以下错误:
IntegrityError at serializers_user_data.owner_id may not be NULL
这是我的代码:
models.py
class User_Data(models.Model):
owner = models.ForeignKey('auth.User', related_name='user_datas')
user_name = models.CharField(max_length = 100, blank = True)
user_email = models.CharField(max_length = 100, blank = True)
user_city = models.CharField(max_length = 50, blank = True)
class Meta:
ordering = ['user_name']
def __unicode__(self):
return self.user_name
view.py
class User_Mixing():
queryset = User_Data.objects.all()
serializer_class = User_Data_Serializers
permission_classes = (IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.owner = self.request.user
print obj.owner
class User_list(User_Mixing, generics.ListCreateAPIView):
pass
class User_detail(User_Mixing, generics.RetrieveUpdateDestroyAPIView):
pass
还帮我修改外键中的related_names。它用于什么目的?
答案 0 :(得分:1)
我使用perform_create方法而不是pre_save
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
答案 1 :(得分:0)
在代码中设置ipdb
def pre_save(self, obj):
import ipdb; ipdb.set_trace()
obj.owner = self.request.user
print obj.owner
并检查request.user属性以了解错误。