HyperlinkedIdentityField returning error only on U

2019-05-26 18:57发布

问题:

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}}

The error I get is:

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.

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.

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

回答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'),

but changing it to:

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

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.