[英]Django File Upload and Rename
User is uploading a .c file of a particular question.用户正在上传特定问题的.c文件。 I want the file to be renamed as 'userid_questionid.c'
我希望将文件重命名为“userid_questionid.c”
My models.py is :我的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 tried this.我试过这个。 But it just creates the folder of user and saves file in it.
但它只是创建用户文件夹并将文件保存在其中。 Please help.
请帮忙。 Thank You.
谢谢。 I need the file to be renamed.
我需要重命名文件。
You just need to change your content_file_name
function.您只需要更改
content_file_name
函数。 The function below will create paths like so: uploads/42_100.c
, where 42
is the user's id, and 100
is the question's id.下面的函数将创建如下路径:
uploads/42_100.c
,其中42
是用户的 id, 100
是问题的 id。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.