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

Question:

I’m trying to implement functionality where user can upload file and choose (in the form) if this file is going to be global (available for everybody) or private (available only for him).
The form would look like this

r

Firstly I have doubled model, view, form etc. where only difference was:

file = models.FileField(upload_to=user_directory_path)

and

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

is what destroys DRY rule. Obviously it’s not what I want to achieve.

So then I tried to make a boolean in the model and changed the upload_to parameter depending on the user’s choice:

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')

Unfortunately it doesn’t work. Does anyone has any idea how to implement that?

Asked By: kashubian

||

Answers:

Just one of this is enough

file = models.FileField(upload_to=user_directory_path)

You don’t want to break DRY or add a useless db column, Let’s dive into the form

# 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)
Answered By: Ahmed I. Elsayed
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.