MS25
MS25

Reputation: 1

django rest: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a `queryset` attribute, or override the `get_queryset()` method

I'm trying to follow a tutorial from the book 'Django for APIs', this tutorial consists on doing a blog project API with django rest framework.

I cant get to work the UserDetail view at url: 'http://127.0.0.1:8000/api/v1/users/int:pk/' it raises the following error ,although queryset is defined in the UserDetail class in views.py:

AssertionError at /api/v1/users/1/

'UserDetail' should either include a queryset attribute, or override the get_queryset() method.

here is the code:

urls.py

views.py

serializers.py

models.py

urls.py:

from django.urls import path
from .views import UserList, UserDetail, PostList, PostDetail

urlpatterns = [
    path('users/',UserList.as_view()),
    path('users/<int:pk>/', UserDetail.as_view()),
    path('',PostList.as_view()),
    path('<int:pk>/', PostDetail.as_view()),
]

views.py:

from django.contrib.auth import get_user_model
from rest_framework import generics

from .models import Post
from .permissions import IsAuthorOrReadOnly
from .serializers import PostSerializer, UserSerializer

# Create your views here.

class PostList(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (IsAuthorOrReadOnly,)
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class UserList(generics.ListCreateAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset_= get_user_model().objects.all()
    serializer_class = UserSerializer

serializers.py:

from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import Post


class PostSerializer(serializers.ModelSerializer):

    class Meta:
        fields = ('id','author','title','body','created_at',)
        model = Post

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields  = ('id','username',)

models.py:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Post(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Upvotes: 0

Views: 554

Answers (1)

Mahrus Khomaini
Mahrus Khomaini

Reputation: 814

Please check your UserDetail, it should queryset not queryset_

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = get_user_model().objects.all()

Upvotes: 1

Related Questions