我正在尝试重命名我的图像。我似乎无法使其正常工作。
class Article(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to=photo_file_name, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
url = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.title
def photo_file_name(self, filename):
extension = filename.split('.')[-1]
filename = 'cover_photo_{}.{}'.format(self.id, extension)
return os.path.join('articles/media/articles/photos/coverphotos/', filename)
所有答案都无法帮助我。我收到一个NameError:名称'photo_file_name'未定义。任何帮助将非常感激。谢谢!
答案 0 :(得分:0)
hi函数不应属于该类
def photo_file_name(self, filename):
extension = filename.split('.')[-1]
filename = 'cover_photo_{}.{}'.format(self.id, extension)
return os.path.join('articles/media/articles/photos/coverphotos/', filename)
class Article(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to=photo_file_name, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
url = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.title
答案 1 :(得分:0)
在模型中添加它,
import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
# add extension as per your requirement, I am using .png
ext = "png"
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.path, filename)
class Article(models.Model):
photo = models.ImageField(upload_to=PathAndRename('images/'), blank=True, null=True)
清除照片文件名称功能。您可以将PathAndRename添加到所有模型中。