【问题标题】:HyperlinkedIdentityField returning error only on User modelHyperlinkedIdentityField 仅在用户模型上返回错误
【发布时间】:2015-09-05 15:42:10
【问题描述】:

我一直在我的许多序列化程序上使用HyperlinkedIdentityField,但是,当我尝试在默认的 Django User 模型上使用它时,我得到一个错误。

class UserSerializer(serializers.ModelSerializer):
    userprofile = serializers.HyperlinkedRelatedField(
        many=False, view_name='user-profile-detail', read_only=True)
    uri = serializers.HyperlinkedIdentityField(
        view_name='user-detail')

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name',
                  'email', 'is_active', 'is_staff', 'is_superuser',
                  'last_login', 'date_joined', 'userprofile', 'uri',)
        read_only_fields = ('id', 'last_login', 'date_joined',)
        extra_kwargs = {'password': {'write_only': True}}

我得到的错误是:

Exception Type: ImproperlyConfigured
Exception Value: Could not resolve URL for hyperlinked relationship using view name
                 "user-detail". You may have failed to include the related model in
                 your API, or incorrectly configured the `lookup_field` attribute
                 on this field.

user-detail 名称确实存在并且在引用该用户的其他表上正常工作。 lookup_field 参数默认使用pkuserprofile 是默认用户模型的 OneToOne。

我想知道这是否与 Django 的默认 AnonymousUser 有一个 pk-1 有关,但我无法验证这一点。

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您可以尝试在超链接序列化程序中传递查找字段吗?

标签: django django-rest-framework


【解决方案1】:

好的,在我发布问题和为此苦苦挣扎数周后的几秒钟内,我意识到问题出在哪里。我认为这与AnonymousUserpk-1 有关是正确的。我原来的 URL 模式是:

url(r'user/(?P<pk>\d+)/$', 'user_detail', name='user-detail'),

但将其更改为:

url(r'user/(?P<pk>[-\d]+)/$', 'user_detail', name='user-detail'),

解决了这个问题。我不允许在 pk 字段中使用连字符 (-)。很简单,但起初对我来说并不是很明显。错误消息也没有任何帮助,这就是为什么我很可能没有立即发现问题。

如果其他人遇到同样的问题,我希望这对他们有所帮助。

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多