У объекта 'str' нет атрибута 'name' Django rest api video post error
Вот мое приложение django rest api для загрузки видео, мой файл models.py находится ниже,
from django.db import models
from django.contrib.auth.models import User
from likevideos.models import Likevideo
class Video(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255,blank=True)
video_file = models.FileField(upload_to='videos/')
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Video by {self.id}: {self.title}"
@property
def like_count(self):
return self.likevideos.count()
@property
def comment_count(self):
return self.videocomments.count()
Вот мой файл views.py,
from rest_framework import generics, permissions, filters
from friends_chats.permissions import IsOwnerOrReadOnly
from rest_framework.response import Response
from .models import Video
from .serializers import VideoSerializer
class VideoListCreateView(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]
queryset = Video.objects.all()
serializer_class = VideoSerializer
filter_backends = [
filters.OrderingFilter,
filters.SearchFilter,
]
search_fields = [
'owner__username',
'title',
]
ordering_fields = [
'like_count',
'comment_count',
'likevideos__created_at',
]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class VideoDetailView(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsOwnerOrReadOnly]
queryset = Video.objects.all()
serializer_class = VideoSerializer
Вот мой сериализатор,
from rest_framework import serializers
from django.core.validators import FileExtensionValidator
from django.core.exceptions import ValidationError as DjangoValidationError
from .models import Video
from .models import Likevideo
class VideoSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
is_owner = serializers.SerializerMethodField()
likevideo_id = serializers.SerializerMethodField()
like_count = serializers.ReadOnlyField()
comment_count = serializers.ReadOnlyField()
class Meta:
model = Video
fields = ['id', 'owner', 'title', 'video_file', 'description', 'created_at', 'updated_at', 'is_owner','likevideo_id','like_count','comment_count']
def validate_video_file(self, value):
# Check file extension
valid_extensions = ['mp4', 'avi', 'mkv', 'mp3']
extension_validator = FileExtensionValidator(allowed_extensions=valid_extensions)
try:
extension_validator(value.name)
except DjangoValidationError as e:
raise serializers.ValidationError(str(e))
# Check file size
max_size = 50 * 1024 * 1024
if value.size > max_size:
raise serializers.ValidationError(f"File size too large. Max size is {max_size} bytes.")
return value
def get_is_owner(self, obj):
request = self.context.get('request')
return request.user == obj.owner
def get_likevideo_id(self, obj):
user = self.context['request'].user
try:
likevideo_instance = Likevideo.objects.get(owner=user, video=obj)
return likevideo_instance.id
except Likevideo.DoesNotExist:
return None
def get_likevideo_count(self, obj):
return obj.like_count
def get_comment_count(self, obj):
return obj.comment_count
Я получаю ошибку при загрузке видео,
AttributeError at /videos/ 'str' object has no attribute 'name'
Я попробовал изменить строку проверки видеофайла с extension_validator(value.name) на value.title или value.file.title