在提交表单之前是否可以将文件上传到django?

时间:2018-01-09 16:40:10

标签: python django forms file upload

我正在开发一个webapp,它允许用户上传相当大的视频文件,并(基于他们填写的表格中的数据)处理它们。目前设置一旦提交表单就开始上传文件(这就是django的工作方式),但我想利用用户忙于填写表单的时间(假设他们开始)首先上传文件。)

这可能吗?我将如何实现这一目标?这是django功能吗?

我现在的方式就是我的视频有这个模型:

class Video(models.Model):
    def user_directory_path_thumbnail(instance, filename):
        # file will be uploaded to MEDIA_ROOT/thumbnails/<identifier>.png
        return 'thumbnails/{0}.png'.format(instance.identifier)

    def user_directory_path_video(instance, filename):
        # file will be uploaded to MEDIA_ROOT/videos/<identifier>.png
        return 'videos/{0}.mp4'.format(instance.identifier)

    uploader    = models.ForeignKey(User, on_delete=models.CASCADE)
    title       = models.CharField(max_length=256)
    identifier  = models.SlugField(blank=True, null=True)
    category    = models.ForeignKey(Category, on_delete=models.CASCADE)
    description_short = models.CharField(max_length=300, default="none")
    description = models.TextField(default="none")
    uploaded    = models.DateTimeField(auto_now_add=True)
    updated     = models.DateTimeField(auto_now=True)
    time        = models.IntegerField()
    thumbnail   = ResizedImageField(size=[320, 180],upload_to=user_directory_path_thumbnail, force_format='PNG')
    type        = models.IntegerField(default=0)
    media       = models.FileField(upload_to=user_directory_path_video, default=settings.MEDIA_ROOT + '/videos/test.mp4')


    # Used to show video title in django admin page instead of 'video object(n)'
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/view/" + self.identifier

和我的上传表单:

class VideoUpdateForm(forms.ModelForm):
    iquery_choices = Category.objects.values_list('description', flat=True)
    category = forms.ChoiceField(choices = iquery_choices)
    videoFile = forms.FileField()
    class Meta:
        model = Video
        fields = [
            'title',
            'description',
            'description_short',
            'time',
            'thumbnail',
            'type',
            'media',
        ]

    def clean_thumbnail(self):
        picture = self.cleaned_data.get("thumbnail")
        if not picture:
            raise forms.ValidationError("No Image")
        else:
            w, h = get_image_dimensions(picture)
            if w/h != (16/9):
                raise forms.ValidationError("Image in wrong aspect ratio (should be 16:9)")
        return picture

我是否需要单独的模型和表单来存档或者是否可以将它们保留在同一模型中?

0 个答案:

没有答案