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.
Serializers.py
post_detail_url = HyperlinkedRelatedField(
view_name="posts-api:detail",
read_only=True,
lookup_field='slug'
)
class PostListSerializer(ModelSerializer):
class Meta:
url = post_detail_url
fields = (
'id',
'url',
'user',
'title',
'content',
'created_at',
'updated_at',
)
model = Post
Urls.py
urlpatterns = [
url(r'^$', PostListAPIView.as_view(), name='list'),
url(r'^create/$', PostCreateAPIView.as_view(), name='create'),
url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', PostUpdateAPIView.as_view(), name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', PostDeleteAPIView.as_view(), name='delete'),
]
Post model
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=200)
content = models.TextField()
posted = models.DateField(db_index=True, auto_now_add=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title