Django 文件上传和重命名

2022-01-20 00:00:00 python django foreign-keys

问题描述

用户正在上传特定问题的 .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)

相关文章