Хочу добавить подписчиков своему пользователю
Модель пользователя
from email.policy import default
from random import choices
from django.contrib.auth.models import AbstractUser
from django.db import models
class UserSonet(AbstractUser):
"""User model for sonet"""
GENDER = (
("male", "male"),
("female", "female"),
("other", "other"),
)
first_login = models.DateTimeField(blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=7, choices=GENDER, default="Unknown")
phone = models.CharField(max_length=14)
biography = models.TextField(max_length=500, blank=True, null=True)
github = models.CharField(max_length=500, blank=True, null=True)
linkedin = models.CharField(max_length=500, blank=True, null=True)
work_place = models.CharField(max_length=150, blank=True, null=True)
work_position = models.CharField(max_length=150, blank=True, null=True)
technology = models.ManyToManyField('Technology', related_name='users')
avatar = models.ImageField(upload_to='user/avatar/', blank=True, null=True)
так же сериализаторы пользователя
from .models import UserSonet
from rest_framework import serializers
class GetUserSonetSerializer(serializers.ModelSerializer):
"""
Filtered display user information
"""
avatar = serializers.ImageField(write_only=True)
class Meta:
model = UserSonet
exclude = (
'password',
'first_login',
'is_active',
'is_staff',
'is_superuser',
'groups',
'user_permissions')
class GetUserSonetPublicSerializer(serializers.ModelSerializer):
"""
Filtered display user information for public
"""
class Meta:
model = UserSonet
exclude = (
'email',
'phone',
'password',
'first_login',
'is_active',
'is_staff',
'is_superuser',
'groups',
'user_permissions')
class UserFollowerSerializer(serializers.ModelSerializer):
"""Serializer for Follower"""
avatar = serializers.ImageField(read_only=True)
class Meta:
model = UserSonet
fields = ('id', 'username', 'avatar')
а теперь к приложению фолловеров
его модель
from django.db import models
from django.conf import settings
class Follower(models.Model):
"""Follower model"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='owner')
subscriber = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='subscribers')
сериализатор
from rest_framework import serializers
from .models import Follower
from src.profiles.serializers import UserFollowerSerializer
class ListFollowerSerializer(serializers.ModelSerializer):
"""List of Follower"""
subscriber = UserFollowerSerializer(many=True, read_only=True)
class Meta:
model = Follower
fields = ('subscriber', )
вьюха
from rest_framework import generics, permissions, views, response
from .models import Follower
from .serializers import ListFollowerSerializer
from src.profiles.models import UserSonet
class ListFollowerView(generics.ListAPIView):
"""Display a list of user Follower"""
permission_classes = [permissions.IsAuthenticated]
serializer_class=ListFollowerSerializer
def get_queryset(self):
return Follower.objects.filter(user=self.request.user)
class AddFollowerView(views.APIView):
"""Add a new Follower"""
permission_classes = [permissions.IsAuthenticated]
def post(self, request, pk):
try:
user = UserSonet.objects.get(id=pk)
except Follower.DoesNotExist:
return response.Response(status=404)
Follower.objects.create(subscriber=request.user, user=user)
return response.Response(status=201)
def delete(self, request, pk):
try:
subcriber = Follower.objects.get(subscriber=request.user, user_id=pk)
except Follower.DoesNotExist:
return response.Response(status=404)
subcriber.delete()
return response.Response(status=204)
Через админку создать фолловеров могу, но если в постмене отправляю запрос на то чтобы вывести фолловеров пользователя вылетает такая ошибка:
Internal Server Error: /api/v1/follower/
Traceback (most recent call last):
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/mixins.py", line 46, in list
return Response(serializer.data)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 768, in data
ret = super().data
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 686, in to_representation
return [
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 687, in
self.child.to_representation(item) for item in iterable
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 522, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/comp/Desktop/Python-Proj/My/social_network-django/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 686, in to_representation
return [
TypeError: 'UserSonet' object is not iterable
[07/Jan/2023 22:12:03] "GET /api/v1/follower/ HTTP/1.1" 500 124758
Думаю, что ошибка где-то в сериализаторах, так как если в админка к сериализаторам отношения не имеет и в ней все ок.