Download and rename a Django file

The user uploads a .c file for a specific question. I want the file to be renamed to "userid_questionid.c"

My models.py:

from django.db import models class users(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) score=models.IntegerField(max_length=3) def __unicode__(self): return self.username class questions(models.Model): question = models.TextField(max_length=2000) qid=models.IntegerField(max_length=2) def __unicode__(self): return self.qid def content_file_name(instance, filename): return '/'.join(['uploads', instance.questid.qid, filename]) class submission(models.Model): user = models.ForeignKey(users) questid = models.ForeignKey(questions) file = models.FileField(upload_to=content_file_name) 

I have tried this. But it just creates a user folder and saves the file in it. Please help. Thanks. I need the file to be renamed.

+5
source share
1 answer

You just need to change the content_file_name function. The following functions are created in the function below: uploads/42_100.c , where 42 is the user identifier, and 100 is the question identifier.

 import os def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = "%s_%s.%s" % (instance.user.id, instance.questid.id, ext) return os.path.join('uploads', filename) 
+7
source

Source: https://habr.com/ru/post/1201767/


All Articles