需要一个使用上传文件处理程序方法上传 Django 大文件的示例

Need an Example of Django big File upload with upload file handler method

在我的一个 Django 项目中,我正在尝试上传文件。文件可以是视频文件,最大可达 20 MB。我正在尝试使用 django 文档中给出的 celery 和 upload_file_handler 方法上传它。

我做的就是它。

class MyVideo(models.Model):
    user = models.ForeignKey(User)
    video = models.FileField(null=True, blank=True, upload_to="video")

    def __unicode__(self):
        return self.user.username

在forms.py

class VideoForm(forms.ModelForm):
    video = forms.FileField(required=False)

    class Meta:
        model = MyVideo
        exclude = ['user']

    def clean_video(self):
        video = self.cleaned_data['video']
        if video and video._size > (10 * 1024 * 1024):
            raise forms.ValidationError("only 10 MB video is allowed")
        return self.cleaned_data['video']

在View.py

class CreateDigitalAssetsView(LoginRequiredMixin, CreateView):

template_name = "video_create.html"
form_class = VideoForm

def get_success_url(self):
    return reverse("video_url")

def form_valid(self, form):
    user = self.request.user
    video = form.cleaned_data['video']

    if video:
        handle_uploaded_file(video)
        # stick here what to do next.

def handle_uploaded_file(f):
    filename, extension = os.path.splitext(video.name)
    with open('media/video/'+filename, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

调用 handled_uploaded_file 后,我被困在这里下一步该做什么。请指导我如何使用 hanldle_uploaded_file 使用此书面文件保存在 django 模型中。

您需要从 handle_uploaded_file 函数中 return 创建文件的路径(相对于 /media 根目录),然后将其保存到模型的视频字段中。

所以像这样:

def handle_uploaded_file(f):
    filename, extension = os.path.splitext(video.name)
    relative_path = "video/%s" % filename
    full_path = "media/%s" % relative_path
    with open(full_path, 'wb+') as destination:
    for chunk in f.chunks():
        destination.write(chunk)
    return relative_path

def form_valid(self, form):
    ...

    if video:
         relative_path = handle_uploaded_file(video)
         form.instance.video = relative_path
         form.instance.save()