0

我的网页可以选择使用表单上传视频,但我想扩展其功能,添加提供 YouTube URL 而不是上传文件的选项。

文件上传没有问题,因为我从模型验证表单:

表格.py

class VideoForm(forms.ModelForm):
    class Meta:
        model = Video
        fields = ('file', 'description', 'url')

模型.py

class Video(models.Model):
    file = models.FileField(upload_to=video_directory_path)
    description = models.TextField(blank=True)
    url = models.CharField(max_length=255, blank=True)

一切正常,但是当我尝试发送视频的 URL 时,form = VideoForm(request.POST, request.FILES)由于 request.FILES 为空,它本身无法正常工作,但我尝试了很多方法,例如:

form = VideoForm(request.POST,
                 MultiValueDict({'file': [open(fname,'r')]}))

并且 VideoForm 总是返回:

<tr><th><label for="id_file">File:</label></th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file" required id="id_file" /></td></tr>
<tr><th><label for="id_description">Description:</label></th><td><textarea name="description" rows="10" cols="40" id="id_description">
</textarea></td></tr>
<tr><th><label for="id_url">Url:</label></th><td><input type="text" name="url" value="https://www.youtube.com/watch?v=kj7wTDK5Vx8" id="id_url" maxlength="255" /></td></tr>

问题是,有没有一种方法可以设置request.FILES本地文件来验证表单?我使用pytube库来下载视频,它工作正常,因为当我这样做时它会显示一个比特流open(fname,'r').read(),然后open(fname,'r')返回{'file': <open file u'markst.mp4', mode 'r' at 0x7f375b654db0>}

我希望我的问题很清楚,并在此先感谢!

4

1 回答 1

1

我设法通过File以下方式使用 Django 的对象来解决它:

from django.core.files import File
from django.utils.datastructures import MultiValueDict

file = open(fname, 'r') # Reads the downloaded video
fileform = File(file)
form = VideoForm(data=request.POST, files=MultiValueDict({'file': [fileform]}))

有了这个,表单对象在做的时候最终通过了验证form.is_valid()

我希望这可以帮助有同样问题的人。

于 2018-06-27T13:47:56.603 回答