【发布时间】:2018-12-06 04:02:34
【问题描述】:
我的网页可以选择使用表单上传视频,但我想扩展其功能,添加提供 YouTube URL 的选项,而不是上传文件。
文件上传没有问题,因为我从模型验证表单:
forms.py
class VideoForm(forms.ModelForm):
class Meta:
model = Video
fields = ('file', 'description', 'url')
models.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>}
我希望我的问题很清楚,在此先感谢!
【问题讨论】:
-
您可以在模板中上传您的表单吗?
-
您可以尝试在您的 html 表单标签中添加 enctype="multipart/form-data" 吗?
-
@hathlogic 问题是处理从后端 URL 下载的视频。从文件上传视频没有问题
标签: django forms file-upload pytube