简体   繁体   中英

Django Rest Framework: Could not resolve URL for hyperlinked relationship using view name "post-detail"

I found a lot of answers to the similar issue, but none of them helped me. I am new to the backend and Django, I already spent a few days trying figure out what I am doing wrong, but no success. I would appreciate any help a lot! So, when I call http://127.0.0.1:8000/users/ {user_name}/ I am getting :

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

If I change HyperlinkedRelatedField on any other field it's working properly...

urls.py

 app_name = 'api'
urlpatterns = [
        url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(),
            name='post-detail'),
        url(r'^users/(?P<username>[\w\-]+)/$', UserPosts.as_view()),
    ]

views.py

class PostDetails(APIView):
    """
        - GET a post

    """

    def get(self, request, post_id):

        post = Post.objects.get(id=post_id)
        post_serializer = PostSerializer(post)

        return Response(post_serializer.data)

class UserPosts(APIView):
    """
        GET all user posts
    """

    def get(self, request, username):
        user = User.objects.get(username=username)
        serializer = UserSerializer(user, context={'request': request})
        return Response(serializer.data)

serializer.py

  class UserSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedRelatedField(many=True,
                                                read_only=True,
                                                view_name='post-detail',
                                                lookup_field='id')
    #  Mandatory for UUID serialization
    user_id = serializers.UUIDField()

    class Meta:
        model = User
        exclude = ('id', 'password')
        read_only_fields = ('created', 'username', 'posts',)


class PostSerializer(serializers.ModelSerializer):

    author = UserSerializer()

    class Meta:
        model = Post
        fields = '__all__'

models.py

     class User(models.Model):
   username = models.CharField(max_length=30, unique=True)
   password = models.CharField(max_length=50)
   email = models.EmailField(unique=True)
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=30)
   phone = models.CharField(max_length=20, blank=False, unique=True)
   user_id = models.UUIDField(editable=False,
                           unique=True,
                           null=False,
                           db_index=True,)
  created = models.DateTimeField()
  id = models.BigAutoField(primary_key=True)

  class Meta:
      ordering = ('created',)

  def __unicode__(self):
      return "Email: %s " % self.email


class Post(models.Model):
   created = models.DateTimeField()
   is_active = models.BooleanField(default=False)
   title = models.CharField(max_length=200, blank=False)
   body_text = models.CharField(max_length=1000, blank=False)
   address = models.CharField(max_length=100)
   author = models.ForeignKey(User, on_delete=models.PROTECT,
                           related_name='posts')
   price = models.DecimalField(max_digits=10, decimal_places=0)
   id = models.BigAutoField(primary_key=True)

  class Meta:
      ordering = ('created',)

  def __unicode__(self):
      return "Title : %s , Author:  %s  " % (self.title, self.author)

Your lookup_field does not match your url one which is post_id

url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(),
        name='post-detail'),

From docs:

  • lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
  • lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.

So you should be fine with this:

posts = serializers.HyperlinkedRelatedField(many=True,
                                            read_only=True,
                                            view_name='post-detail',
                                            lookup_url_kwarg='post_id')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM