HyperlinkedIdentityField仅在用户模型上返回错误 [英] HyperlinkedIdentityField returning error only on User model
问题描述
我已经在许多序列化器上使用了 HyperlinkedIdentityField
,但是当我尝试在默认的Django User
model我收到一个错误。
I have been using the HyperlinkedIdentityField
on many of my serializers, however, when I try to use it on the default Django User
model I get an error.
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
参数默认使用 pk
。 userprofile
是默认用户模型的OneToOne。
The user-detail
name definitely does exist and works correctly on other tables that reference the user. The lookup_field
argument is defaulted to using the pk
. The userprofile
is a OneToOne to the default User model.
我想知道它是否与Django的 AnonymousUser
具有 pk
-1
,但我无法验证这一点。
I was wondering if it had something to do with Django's default AnonymousUser
having a pk
of -1
, but I haven't been able to verify this.
任何帮助将非常感谢。谢谢
Any help would greatly be appreciated. Thanks
推荐答案
好的,几秒钟后,我发布了这个问题,几周的努力,我意识到问题是什么。我认为它与 AnonymousUser
有 pk
有关 - 1
。我的原始网址格式是:
OK, seconds after I posted the question and weeks of struggling with this I realized what the problem was. I was right to think it had something to do with the AnonymousUser
having a pk
of -1
. My original URL pattern was:
url(r'user/(?P<pk>\d+)/$', 'user_detail', name='user-detail'),
但将其更改为:
url(r'user/(?P<pk>[-\d]+)/$', 'user_detail', name='user-detail'),
修复了问题。我不允许 pk
字段中的连字符( - )。简单,但是起初我不是很明显。错误消息也没有任何帮助,这就是为什么我很可能没有立即看到问题。
fixed the problem. I wasn't allowing the hyphen (-) in the pk
field. Simple, but it wasn't very obvious to me at first. The error message was not at all helpful either, which is why I most likely didn't see the problem right away.
我希望这有助于别人,如果他们有同样的问题。
Well I hope this helps others if they are having the same issue.
这篇关于HyperlinkedIdentityField仅在用户模型上返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!