【发布时间】:2021-05-30 03:51:57
【问题描述】:
我已经做了几个 django 项目,现在正在试验其余的框架。我正在尝试配置我的网址,以便 url /testuser/ 将带您到用户名“testuser”的用户的个人资料页面。非常简单的任务,我可以使用slug_field 在常规 django 中管理,但我想我不太了解如何正确配置 REST url。任何帮助表示赞赏。代码如下。
仅供参考,如下所示,我使用的是CustomUser 模型,通过OneToOneField 链接到Profile 模型。用户名存储在CustomUser 模型中。但是,个人资料页面将使用ProfileSerializer 填充。
我认为问题可能是我从相关模型 CustomUser 访问“用户名”的方式 - 但我可能是错的(可能,哈哈)。有人知道吗?
我当前的代码抛出错误:
Expected view ProfileView to be called with a URL keyword argument named "username". Fix your URL conf, or set the .lookup_field attribute on the view correctly.
users.models
class CustomUser(AbstractBaseUser):
username = models.CharField(
verbose_name='username',
max_length=40,
unique=True,
)
...
profiles.models
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='profile'
)
...
profiles.serializers
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(read_only=True, source="user.username")
class Meta:
fields = ('username', 'display_name', 'profile_pic',
'bio', 'following', 'modified', 'est', )
model = Profile
lookup_field = 'username'
profiles.views
class ProfileView(generics.RetrieveUpdateAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'username'
profiles.urls
urlpatterns = [
path('<str:slug>/', PostDetail.as_view(), name='self_profile'),
]
感谢您的帮助。
【问题讨论】:
标签: django django-rest-framework django-urls