Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - Django File Upload and Rename

User is uploading a .c file of a particular question. I want the file to be renamed as 'userid_questionid.c'

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...