Reputation: 191
AssertionError occurs when posting using django rest framework The process before an error occurs is this
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('post' , views.PostViewSet)
# print("router.urls : " , router.urls)
urlpatterns = [
path('public/' , views.PublicPostListAPIView.as_view()),
path('', include(router.urls)),
]
view
from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
from .serializers import PostSerializer
from .models import Post
class PublicPostListAPIView(generics.ListAPIView):
queryset = Post.objects.filter(is_public=True)
serializer_class = PostSerializer
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
serializers.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from instagram.models import Post
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ['username','email']
class PostSerializer(ModelSerializer):
author = AuthorSerializer()
class Meta:
model = Post
fields = [
'pk',
'author',
'message',
'created_at',
'updated_at',
'is_public',
]
http://127.0.0.1:8000/post/
3.posting
4.error occured like below
thanks for let me know how to fix it
Upvotes: 0
Views: 48
Reputation: 741
It's assuming to save the author
details you provided in your PostSerializer
. You can have your own create() method like this -
def create(self, validate_data):
data = validated_data
author = data.get('author')
# You can use author details here
data.pop('author')
return Post.objects.create(**data)
Upvotes: 1