Django Storage 应用程序,不同 "upload_to" 取决于用户的选择

Django Storage app, different "upload_to" depending on user's choice

我正在尝试实现用户可以上传文件并选择(在表单中)此文件是全局文件(所有人可用)还是私有文件(仅供他使用)的功能。 表格看起来像这样

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

file = models.FileField(upload_to=user_directory_path)

file = models.FileField(upload_to='global files/')

是什么破坏了DRY规则。显然这不是我想要达到的。

然后我尝试在模型中做一个布尔值,并根据用户的选择更改 upload_to 参数:

class FileModel(models.Model):
    title = models.CharField(max_length=50, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    file = models.FileField(upload_to=user_directory_path)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    STATUS = (
      (1, ('Global file')),
      (2, ('My file')),
      )
    status = models.CharField(max_length = 30, choices=STATUS, default=2)
    if status == 'My file':
        file = models.FileField(upload_to=user_directory_path)

    elif status == 'Global file':
        file = models.FileField(upload_to='global files')

很遗憾,它不起作用。有人知道如何实现吗?

其中一个就够了

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)