Django FileField 存储选项
我有一个模型:
class UserProfile(models.Model):
#..........
photo = models.ImageField(upload_to = get_upload_file_name,
storage = OverwriteStorage(),
blank = True, null = True,
height_field = 'photo_height',
width_field = 'photo_width')
这是我的存储功能:
class OverwriteStorage(FileSystemStorage):
def _save(self, name, content):
self.delete(r'.*')
return super(OverwriteStorage, self)._save(name, content)
def get_available_name(self, name):
return name
我想做到以下两件事:
每当用户上传一个文件(比如一张图片)时,我想删除旧的文件,不管名字是否相同。我尝试过删除与上面正则表达式匹配的任何东西,但这并没有成功。
如果用户上传了一张叫“me.jpg”的图片,我想根据用户的用户名给它重新命名。例如,我会做类似于
return super(OverwriteStorage, self)._save(SOMETHING_ELSE_HERE, content)
的操作。我该怎么做?我可以给 OverwriteStorage 函数传递一个额外的参数吗?
还有一个额外的问题:我为这个表单创建了一个 ModelForm。这样用户就可以上传图片。当有人点击“选择文件”时,会弹出一个窗口,让他们浏览并选择照片。我该如何只显示某些文件呢?(例如,只显示 .jpg 和 .jpeg 文件)
谢谢!
编辑: get_upload_file_name
函数
def get_upload_file_name(instance, filename):
return "%s/%s/profile_photo/%s" % (instance.user.username[0].lower(), instance.user.username, filename)
编辑2: 我已经包含了我的 models.py
import datetime
import os
import urllib2, urlparse
import re
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles import finders
from django.conf import settings
from django.core.files.base import ContentFile
from django.forms import widgets
now = datetime.datetime.now()
def get_upload_file_name(instance, filename):
now = datetime.datetime.now()
file_name = str(now.year) + '_' + \
str(now.month) + '_' + \
str(now.day) + '_' + \
str(now.hour) + '_' + \
str(now.minute)+ '_' + \
str(now.second)+ '.' + \
filename.split('.')[-1]
return "%s/%s/profile_photo/%s" % (instance.user.username[0].lower(),
instance.user.username,
file_name)
class OverwriteStorage(FileSystemStorage):
def _save(self, name, content):
self.delete(name)
return super(OverwriteStorage, self)._save(name, content)
class UserProfileManager(models.Manager):
def create_user_profile(self, user):
user_profile = self.create(user = user)
return user_profile
class UserProfile(models.Model):
### it is now.year - 13 because legitimate persons on this website should be over 14 years old
YEARS = tuple(
zip([format(x,'04d') for x in range(now.year-120, now.year-13)],
[format(x,'04d') for x in range(now.year-120, now.year-13)]
)
)
MONTHS = (
('January','January'),('February','February'),('March','March'),('April','April'),
('May','May'), ('June','June'),('July','July'),('August','August'),
('September','September'),('October','October'),('November','November'), ('December', 'December')
)
GENDERS = (('M', 'Male'), ('F', 'Female'))
user = models.OneToOneField(User, related_name = 'MoreAboutUser', unique=True, verbose_name=_('user'))
year_of_birth = models.CharField(max_length=10, blank = True, null = True, choices=YEARS)
month_of_birth = models.CharField(max_length=10, blank = True, null = True, choices=MONTHS)
gender = models.CharField(max_length=1, blank = True, null = True, choices=GENDERS)
photo = models.ImageField(upload_to = get_upload_file_name,
blank = True, null = True,
height_field = 'photo_height',
width_field = 'photo_width',
#widget = widgets.FileInput(attrs={'accept': 'image/gif,image/png,image/jpeg'})
)
photo_height = models.PositiveIntegerField(blank = True, default = 0)
photo_width = models.PositiveIntegerField(blank = True, default = 0)
creation_time = models.DateTimeField(auto_now_add = True, auto_now = False)
update_time = models.DateTimeField(auto_now_add = False, auto_now = True)
class Meta:
verbose_name = _('user profile')
verbose_name_plural = _('user profiles')
def __unicode__(self):
return self.user.username
objects = UserProfileManager()
def get_profile_photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url
else:
return '/static/images/generic_profile_photo.jpg'
def create_user_profile(sender, instance, created, **kwargs):
if created:
try:
profile = UserProfile.objects.create_user_profile(user = instance)
profile.save()
except:
pass
post_save.connect(create_user_profile, sender=User)
1 个回答
存储API并不知道你的模型是什么样的,所以它无法考虑其他字段的值——它不知道存储在那个字段里的旧文件名,也不知道哪个用户拥有这个模型记录。
你在给ImageField
提供upload_to = get_upload_file_name
选项的方向上是对的;get_upload_file_name
这个函数(你在问题中没有提供)能够根据用户的信息来构建图片的文件名,因为它可以获取到模型实例的引用,这样就知道哪个用户拥有这个模型实例。
至于删除旧文件,你可能需要在模型的save()
方法中实现这个功能。到那时,从现有的模型实例中找到旧文件名已经太晚了,因为它的photo
字段已经被更新为新值;不过,你仍然可以从数据库中获取现有记录的副本,并通过它来删除旧文件。下面是一个实现的例子:
class UserProfile(models.Model):
...
def save(self, *args, **kwargs):
# grab a copy of the old record from the database
oldrec = type(self).objects.get(pk=self.pk)
# save the current instance, and keep the result
result = super(UserProfile, self).save(*args, **kwargs)
# if the path is the same, the file is overwritten already
# and no deletion is necessary
if oldrec.photo.path != self.photo.path:
oldrec.photo.delete()
# return the result received from the parent save() method
return result
为了指定可以接受的文件类型,你需要在为你的字段渲染的<input>
标签中提供一个accept
属性;你需要在自定义表单中重写这个小部件。