I have this model:
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')
And this is my storage function:
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
How can I do the following 2 things:
Whenever a user uploads a file (i.e. an image), I want to delete the old one, no matter if the name is the same or not. I tried to delete anything that matches the regex above, but this is not working.
If the user uploads an image called "me.jpg" I want to rename it differently, depending on the user username for example. So I will do something like
return super(OverwriteStorage, self)._save(SOMETHING_ELSE_HERE, content)
How to do this? can I pass an additional parameter to the OverwriteStorage funcion?
And an additional third question: I've created a ModelForm for this form. So a user can upload an image. So when someone presses 'choose file', a windows window pops up in order to browse and choose a photo. How can I only display certain files here? (eg. only .jpg and .jpeg files)
Thanks!
EDIT: the get_upload_file_name
function
def get_upload_file_name(instance, filename):
return "%s/%s/profile_photo/%s" % (instance.user.username[0].lower(), instance.user.username, filename)
EDIT2: I have included my 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)