Django 文件上传和重命名

Django File Upload and Rename(Django 文件上传和重命名)
本文介绍了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 文件上传和重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)