ImproperlyConfigured at /snippet/5 Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the
lookup_field
attribute on this field.
models.py
from email.policy import default
import imp
from tkinter import CASCADE
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
from django.contrib.auth.models import User
import snippets
# Create your models here.
LEXERS=[item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES=sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES=sorted([(item,item)for item in get_all_styles()])
class Snippet(models.Model):
created=models.DateTimeField(auto_now_add=True)
title=models.CharField(max_length=100,blank=True,default='')
code=models.CharField(max_length=250,default="0")
linenos=models.BooleanField(default=False)
language=models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100)
style=models.CharField(choices=STYLE_CHOICES,default='friendly',max_length=100)
owner=models.ForeignKey('auth.User',related_name='snippets',on_delete=models.CASCADE)
class Meta:
ordering=['created']
permissions.py
import imp
from rest_framework import permissions
class IsOwnerReadOnly(permissions.BasePermission):
"""custom permissions to only allow owners of an oject to edit
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
serializers.py
from operator import mod
from numpy import source
from .models import *
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model=Snippet
fields = ['url', 'id', 'owner',
'created', 'title', 'linenos', 'language', 'style']
# fields='__all__'
# fields=['id','url','owner']
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets=serializers.HyperlinkedRelatedField(lookup_field = 'username',many=True,view_name='snippet-details',read_only=True)
owner=serializers.ReadOnlyField(source='owner.username')
class Meta:
model= User
fields=['id','username','snippets','owner']
views.py
from snippets.models import Snippet
from snippets.permissions import IsOwnerReadOnly
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerReadOnly
from rest_framework import permissions
class snippet_list(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class snippet_detail(generics.RetrieveUpdateDestroyAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly,IsOwnerReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
########################## authentication purspose #####################################################
from django.contrib.auth.models import User
from .serializers import *
from rest_framework import permissions
class UserList(generics.ListAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
####################################### using hyperlinking for relationships #################################################################
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
urls.py(api)
from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import path,include
from snippets import views
from .views import *
urlpatterns=format_suffix_patterns([path('',views.api_root),
path('snippet/',views.snippet_list.as_view(),name='snippet-list'),
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
path(' ',views.UserList.as_view(),name='user-list'),
path('Users/<int:pk>',views.UserDetail.as_view(),name='user-details'),
])
urls.py(main project)
from django.contrib import admin
# from snippets.urls import *
# from snippets.views import *
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('snippets.urls')),
]
########################## authentication purspose #####################################################
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
I'm new for django but learning and implementing and also sorting errors. But I got stuck with this error for 2 days. I done many changes but still not working.
It appears to me that you misspelled the url name in the urls.py
You have
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
replace it with
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-detail')
remove the "s" from the name
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.