Django Storage应用,取决于用户的选择,不同的“ upload_to”

我正在尝试实现一些功能,用户可以上传文件并选择(以表格形式)此文件是全局文件(每个人都可以使用)还是私有文件(仅他可以使用)。 表单看起来像这样

Django Storage应用,取决于用户的选择,不同的“ upload_to”

首先,我将模型,视图,表格等加倍,唯一的区别是:

id | resultId
1  | 11
2  | 12
3  | 20
4  | 21
5  | 15

file = models.FileField(upload_to=user_directory_path)

是破坏DRY规则的原因。显然,这不是我想要实现的目标。

因此,我然后尝试在模型中创建布尔值,并根据用户的选择更改了file = models.FileField(upload_to='global files/') 参数:

upload_to

不幸的是,它不起作用。有谁知道如何实现?

HELLO_JAVA521 回答:Django Storage应用,取决于用户的选择,不同的“ upload_to”

其中之一就足够了

file = models.FileField(upload_to=user_directory_path)

您不想破坏 DRY 或添加无用的db列,让我们深入了解表单

# forms.py 

class MyForm(...):
    ...
    def form_valid(self,form):
       # here you have access to form.data and form.instance (the instance of your model)
       # I'll make it pseudo and you translate to python
       # get what the user chose from form.data in a variable (print it first to see it)
       # edit the form.instance.file depending on it. (instance of your model
       # think of it as my_instance = form.instance)
本文链接:https://www.f2er.com/2470924.html

大家都在问