[英]Upload Videos into Django Model FileField with Python Script
我正在尝试使用下面的 python 脚本将一个小视频文件(10mb)上传到 Django model FileField。 我有一个表单设置,但想通过脚本绕过它。 当我运行脚本时,我得到 http 响应 200 但视频文件没有出现在相关文件夹中。 问题是什么?
pythonscript.py
# uplaod video file to django model
f = open('/path/to/video.mp4', 'rb')
urls='http://127.0.0.1:8000/showvideo'
r=requests.post(urls, files= {'videofile':f})
print(r.status_code)
models.py
from django.db import models
class VideoUpload(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["name", "videofile"]
views.py
from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def showvideo(request):
lastvideo= VideoUpload.objects.last()
videofile = lastvideo.videofile if lastvideo else None
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'video.html', context)
我玩弄了这个并意识到名称字段干扰了上传。 我从 models.py 和 forms.py 中删除了名称字段,视频文件现在上传成功并出现在相关文件夹中。
models.py
from django.db import models
class VideoUpload(models.Model):
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["videofile"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.