Django Rest Framework:无法使用视图名称“post-detail”

时间:2017-12-27 04:55:40

标签: python django django-rest-framework backend django-serializer

我找到了类似问题的很多答案,但没有一个能帮助我。 我是后端和Django的新手,我已经花了几天时间试图弄清楚我做错了什么,但没有成功。 我非常感谢任何帮助! 因此,当我致电 http://127.0.0.1:8000/users/ {user_name} / 时 我得到了:

  

NotperlyConfigured:无法使用视图名称“post-detail”解析超链接关系的URL。您可能未能在API中包含相关模型,或者在此字段上错误地配置了lookup_field属性。

如果我在其他任何字段上更改 HyperlinkedRelatedField ,它就能正常运行......

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)

1 个答案:

答案 0 :(得分:2)

您的lookup_field与您的网址post_id

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

来自docs:

  • lookup_field - 目标上应该用于查找的字段。应该对应于引用视图上的URL关键字参数。默认为&#39; pk&#39;。
  • lookup_url_kwarg - 在URL conf中定义的与查找字段对应的关键字参数的名称。默认使用与lookup_field相同的值。

所以你应该没问题:

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