[Django] How to replace an image using ModelForm

December 14th, 2009

I have a user profile model which holds their ‘mugshot’ image. I’m using modelForm to to present a profile update form. It was easy to build a working form, but now I need a couple of tweaks to the image:

1) it saves with the filename that the user provides; I rather dictate the filename to use. I thought I’d just use the PK of the model, and the same file extension eg: “443.jpg”

2) it should replace the existing image, not append an underscore like “443___.jpg”.

Here’s my model and form:

class Member(models.Model):
    home_phone      = models.CharField(max_length=10, blank=True)
    image           = models.ImageField(upload_to='members', default="default.png")
    ...

class MemberProfileForm(forms.ModelForm):
   home_phone      = AUPhoneNumberField(required=False)

   class Meta:
       model = Member
       exclude = ('email','password','create_date','last_login','is_active')

This seems to solve it by altering the filename and deleting the existing file prior to the form save.

form = MemberProfileForm(request.POST, request.FILES, instance=request.member)
if form.is_valid():
    if form.cleaned_data['image']:
        (path, extension) = os.path.splitext(form.cleaned_data['image'].name)
        form.cleaned_data['image'].name = ('%s%s' % (request.member.id, extension))
        request.member.image.delete()
    form.save()

… excepting that most people probably want ‘request.user’, where I have ‘request.member’.

  1. No comments yet.
  1. No trackbacks yet.