我正在尝试使用 Django REST 发布“记录”。我希望 Django 自动设置登录用户的用户 ID。
视图.py:
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
序列化程序.py:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'created', 'owner', 'desc')
read_only_fields = ('owner',)
模型.py:
class Item(models.Model):
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey('appserver.MyUser', related_name='appserver')
desc = models.CharField(max_length=100, blank=True, default='')
我正在使用来自 django-rest-authemail 0.1.4 的 EmailAbstractUser:
视图.py:
class MyUser(EmailAbstractUser):
date_of_birth = models.DateField('Date of birth', null=True, blank=True)
objects = EmailUserManager()
任何帮助表示赞赏。