使用自定义用户模型(DRF)显示作者链接

时间:2020-04-01 16:14:44

标签: django-rest-framework

我通过AbstractBaseUser-

有一个自定义用户模型
class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)
    created = models.DateTimeField(default=timezone.now)
    image = models.ImageField(upload_to=get_user_dir_path,
                              default='user_placeholder/user_image_placeholder.png')
    points = models.IntegerField(default=0)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

因此,我有第二个模型Post,在这里可以看到“作者”已提交-

author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

然后,我创建了PostsViewSet。检查我的序列化器-

class PostSerializer(serializers.HyperlinkedModelSerializer):
    isFan = serializers.SerializerMethodField()
    id = serializers.ReadOnlyField()
    created = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True)
    author = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True)

    class Meta:
        model = Post
        read_only_fields = ('users',)
        fields = '__all__'

    def get_isFan(self, obj) -> bool:

        user = self.context.get('request').user
        if user.is_anonymous:
            return None
        else:
            return services.isFan(obj, user)

此后,创建帖子时出现错误-

无法使用视图名称“ user-detail”解析超链接关系的URL。您可能没有在API中包含相关模型,或者在此字段上错误地配置了lookup_field属性。

如何解决?

1 个答案:

答案 0 :(得分:0)

serializers.HyperlinkedRelatedField尝试根据您的URL架构找到可以检索特定作者的URL API。

您可能错误地配置了urls.py