定义文件路径以在Django中保存用户上传的文件

时间:2018-11-17 12:20:47

标签: python django django-forms django-views

考虑一下我们是否有一个包含一个字段的表单,供用户这样上传文件:

class PoscastForm(forms.ModelForm):
    class Meta:
        fields = ("title", "message", "channel", "file", "tag")
        model = models.Podcast

    def __ini__(self, *args, **kwargs):
        user = kwargs.pop("user", None)
        super().__init__(*args, **kwargs)

        if user is not None:
            self.fields["channel"].queryset = (
                models.Channel.objects.filter(
                    pk__in = user.channels.value_list('channel__pk')
                )
            )

以及播客模型:

class Podcast(models.Model):
    title = models.CharField(max_length=255, default='')
    user = models.ForeignKey(User, related_name="podcasts", 
on_delete=models.CASCADE, unique=False)
    created_at = models.DateTimeField(auto_now=True)
    channel = models.ForeignKey(Channel, related_name="podcasts", 
null=True, blank=True,
        on_delete=models.CASCADE)
    message = models.TextField(blank=True, null=True)
    message_html = models.TextField(editable=False)
    tag = models.ForeignKey('podcasts.Tag', related_name="podcasts", 
null=True, blank=True, on_delete=models.CASCADE)
    file = models.FileField(blank=True, null=True, default='')

因此,当用户上传他的附件时,它将保存在我项目的根目录中!如何更改方向路径? 此表单的视图如下所示:

class CreatePodcast(LoginRequiredMixin, SelectRelatedMixin, 
generic.CreateView):
    fields = ("title", "message", "channel", "file", "tag")
    model = models.Podcast

   def form_valid(self, form):
       self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

1 个答案:

答案 0 :(得分:2)

根据documentation,您可以在模型定义中定义文件路径

file = models.FileField(blank=True, null=True, default='', upload_to="your/path/")

如果您定义了MEDIA_ROOT,则上传的文件将被发送到MEDIA_ROOT的子目录upload_to。有关更多详细信息,请参见storage文档。

您还可以定义用户明智的上传目录。来自文档:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

# model defination
file = models.FileField(upload_to=user_directory_path)