So, I'm a newb in Django and I've defined a custom user, users are allowed to update their profiles using a ModelForm however each time I submit the form it uploads and proceses the thumbnail again, how can I check if the upload field has changed and exclude it from the submission if it has not?
here is my code:
views.py
@login_required
def account_edit(request):
u = AccountUser.objects.get(pk=request.user.id)
if request.method == 'POST':
form = UserChangeForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
form.save()
else:
form = UserChangeForm(instance=request.user)
return render_to_response('accounts/account.html', locals(), RequestContext(request))
models.py
class AccountUser(AbstractUser):
about = models.TextField(blank=True, null=True)
occupation = models.CharField(max_length=255, blank=True, null=True)
avatar = models.ImageField(upload_to="accounts/avatars", blank=True, null=True)
slug = models.SlugField(default='', blank=True)
following = models.ManyToManyField('AccountUser', related_name="followed_by", blank=True, null=True)
thumbnail = models.ImageField(upload_to="accounts/avatars/thumbnails", blank=True, null=True)
def save(self, *args, **kwargs):
if self.avatar is not None:
img = Image.open(self.avatar.file)
thumbnail = ImageOps.fit(img, (220, 220,), method=Image.ANTIALIAS)
temp_handle_img = StringIO()
img.save(temp_handle_img, 'png')
temp_handle_img.seek(0)
temp_handle_thumbnail = StringIO()
thumbnail.save(temp_handle_thumbnail, 'png')
temp_handle_thumbnail.seek(0)
suf_thumbnail = SimpleUploadedFile(os.path.split(self.avatar.name[-1],temp_handle_thumbnail.read(), content_type='image/png')
fname_thumbnail = "%s.png" % os.path.splitext(self.avatar.name)[0]
sufImg = SimpleUploadedFile(os.path.split(self.avatar.name)[-1], temp_handle_img.read(), content_type='image/png')
fnameImg = "%s.png" % os.path.splitext(self.avatar.name)[0]
self.thumbnail.save(fname_thumbnail, suf_thumbnail, save=False)
self.avatar.save(fnameImg, sufImg, save=False)
if not self.slug:
self.slug = slugify(self.username)
super(AccountUser, self).save(*args, **kwargs)
You should remove 'thumbnail' from your model fields and set it as a def
. thumbnail doesn't seem to need to be in db.
Edit:
I think, you should hash your picture for see if changed. Use hashlib.md5
for example.
def save(self, *args, **kwargs):
if self.avatar is not None:
# Do your stuff
cur_file = AccountUser.objects.get(pk=self.pk).avatar.file
cur_file_hash = md5(cure_file.read()).hexdigest()
new_file_hash = md5(temp_handle_img.read()).hexdigest()
if cur_file_hash != new_file_hash:
# Do some stuff
I don't think I exactly resolve it, but it should give you a way...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.