本文介绍了Django 文件上传和重命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
用户正在上传特定问题的 .c 文件.我希望将文件重命名为userid_questionid.c"
User is uploading a .c file of a particular question. I want the file to be renamed as 'userid_questionid.c'
我的 models.py 是:
My models.py is :
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.
推荐答案
你只需要改变你的 content_file_name
函数.下面的函数将创建如下路径:uploads/42_100.c
,其中42
是用户的ID,100
是问题的ID.
You just need to change your content_file_name
function. 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.
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)
这篇关于Django 文件上传和重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!