简体   繁体   中英

Upload Videos into Django Model FileField with Python Script

I am trying to upload a small video file (10mb) to a Django model FileField with the python script below. I have a form setup but want to bypass this with the script going forward. When I run the script I get http response 200 but the video file does not appear in the relevant folder. What is the problem?

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)

I played around with this and realised the name field was interfering with the upload. I removed the name field from models.py and forms.py and the video file now uploads successfully and appears in the relevant folder.

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM