I
I
Ilya Pochepko2016-06-02 13:21:57
Django
Ilya Pochepko, 2016-06-02 13:21:57

How to implement automatic file save path generation in Django?

There is such a user model

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(max_length=100, verbose_name="Имя")
    last_name = models.CharField(max_length=100, verbose_name="Фамилия")
    study_group = models.CharField(max_length=100, verbose_name="Группа")

    def __str__(self):
        return self.user.username

This is how the loading of models.py files is implemented:
class Article(models.Model):
    file_obj = models.FileField(upload_to='files', verbose_name='Файл')

views.py:
def Upload_file(request):
  if request.method == 'POST':
    form = ArticleForm(request.POST, request.FILES)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect('/theory/all')
  else:
    form = ArticleForm()

  return render(request, 'file_upload.html', {'form': form})

Attention, question, dear experts:
How to implement the save path in such a way that the file loaded by the user is placed in
{MEDIA_ROOT}/files/{username}/{YY.MM.DD}/
User authentication is implemented, so username must be the user of the current session

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2016-06-02
@un1t

You can pass a function to the upload_to argument. If you have enough time, then you can:

upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

O
Oscar Django, 2016-06-02
@winordie

djbook.ru/rel1.9/ref/models/fields.html#django.db....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question