django 为什么我得到一个错误,说明不支持的文件时,我已经指定我想使用.mp3

ffvjumwh  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(140)

我试图用Django和Postgresql制作一个音乐播放器,我创建了一个歌曲模型,除了当我试图上传一个扩展名为.mp3的音频文件时,它在数据库中工作。有人知道如何解决这个问题吗?谢啦,谢啦
网址:models.py

from django.db import models
    from django.contrib.auth.models import User
    from cloudinary.models import CloudinaryField
    from recordroomapp.helper import get_audio_length
    from .validators import validate_is_audio

    class Artist(models.Model):
        artist = models.CharField(max_length=100, unique=True)
        slug = models.SlugField(max_length=100, unique=True)
        created_on = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.artist
class Song(models.Model):
        title = models.CharField(max_length=100, unique=False)
        slug = models.SlugField(max_length=100, unique=True)
        song = models.FileField(
            upload_to='media/', validators=[validate_is_audio], null=True)
        song_length = models.DecimalField(
             blank=True, max_digits=10, decimal_places=2, null=True)
        songinfo = models.ForeignKey(
            "Artist", on_delete=models.CASCADE, related_name='song_post', null=True)
        updated_on = models.DateTimeField(auto_now=True)
      # featured_image = CloudinaryField('image', default='placeholder')
        created_on = models.DateTimeField(auto_now_add=True)
        likes = models.ManyToManyField(User, related_name='song_likes', blank=True)

        class Meta:
            ordering = ['-created_on']

        def __str__(self):
            return self.title

        # def __init__(self):
        #     return self.song_length

        def save(self, *args, **kwargs):
            if not self.song_length:
                 audio_length = get_audio_length(self.song)
                self.song_length = f'{audio_length:.2f}'

            return super().save(*args, **kwargs)

        def number_of_likes(self):
            return self.likes.count()
class Comment(models.Model):
        post = models.ForeignKey(
            Song, on_delete=models.CASCADE, related_name='comments')
        name = models.CharField(max_length=100)
        email = models.EmailField()
        body = models.TextField()
        created_on = models.DateTimeField(auto_now_add=True)
        approved = models.BooleanField(default=False)

        class Meta:
            ordering = ['created_on']

        def __str__(self):
             return f"Comment {self.body} by {self.name}"

网址:views.py

from django.shortcuts import render, get_object_or_404, HttpResponse
    from django.views import generic, View
    from .models import Song

    class SongList(generic.ListView):
        model = Song
        queryset = Song.objects.order_by('-created_on')
        template_name = 'index.html'

    class SongDetail(View):

        def get(self, request, slug, *args, **kwargs):
            queryset = Song.objects.all()
            post = get_object_or_404(queryset, slug=slug)
            comments = post.comments.filter(approved=True).order_by('-created_on')
            liked = False
            if post.likes.filter(id=self.request.user.id).exists():
                liked = True

            return render(
                request,
                "song_detail.html",
                {
                    "song": queryset,
                    "post": post,
                    "comments": comments,
                    "liked": liked
                },
            )


网址:admin.py

from django.contrib import admin
    from .models import Artist, Song, Comment
    from django_summernote.admin import SummernoteModelAdmin

    @admin.register(Artist)
    class ArtistAdmin(SummernoteModelAdmin):
        list_display = ('artist', 'slug', 'created_on')
        search_fields = ['artist']

    @admin.register(Song)
    class SongAdmin(SummernoteModelAdmin):
        prepopulated_fields = {'slug': ('title',)}
        list_filter = ['created_on']
        summernote_fields = ('content')
        list_display = ('title', 'slug', 'song', 'created_on')
        search_fields = ['title', 'content']


网址:validators.py

import os
    from django.core.exceptions import ValidationError
    from mutagen.mp3 import MP3

    def validate_is_audio(file):

        try:
            audio = MP3(file)

            if not audio:
                raise TypeError()

            first_file_check = True

        except Exception as e:
            first_file_check = False

        if not first_file_check:
            raise ValidationError('Unsupported file type.')
        valid_file_extensions = ('.mp3')
        ext = os.path.splitext(file.name)[1]
        if ext.lower() not in valid_file_extensions:
            raise ValidationError('Unacceptable file extension.')


网址:helper.py

from mutagen.mp3 import MP3

    def get_audio_length(file):
        audio = MP3(file)
        return audio.info.length


我已经发布了上面的文件,导致错误,这表明该文件不受支持。

dced5bon

dced5bon1#

我能发现线路中的错误

valid_file_extensions = ('.mp3')

字符串
应该是的

valid_file_extensions = ('.mp3', )


或者是

valid_file_extensions = ['.mp3']


当你想用一个变量创建一个元组时,你应该在末尾添加一个逗号,这样:(<some_var>)等于<some_var>,但不是一个带有此var的元组,而是当您添加逗号时它的元组。(<some_var>, )

>>> type( (123) )
<class 'int'>
>>> type( (123, ) )
<class 'tuple'>
>>>

相关问题