Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading Profile Image using Django ModelForm

I've looked around at related questions, but none of the answers seem to work. I'm trying to upload a profile image for a user and have it replace (overwrite) the current image. Upon saving the image I want to change the filename to the user id. In it's current form the image will upload, but it won't replace the existing image (e.g. it'll be saved as 2_1.png).

class PhotoForm(forms.ModelForm):
    def save(self):
        content_type = self.cleaned_data['photo'].content_type.split('/')[-1]
        filename = '%d.%s' % (self.instance.user.id, content_type)

        instance = super(PhotoForm, self).save(commit=False)
        instance.photo = SimpleUploadedFile(filename, self.cleaned_data['photo'].read(), content_type)
        instance.save()
        return instance

    class Meta:
        model = UserProfile
        fields = ('photo',)

def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            form.save()
    else:
        form = PhotoForm()
    return render(request, 'photo_form.html', {'form': form})
like image 379
dvw Avatar asked Aug 31 '11 16:08

dvw


People also ask

How do I upload a PFP?

Updated mobile browser experienceTap in the top right of Facebook, then tap your name. Tap your profile picture. Choose to Take Photo, Upload Photo, Add Frame or View Profile Picture. Tap Save.


1 Answers

def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            handle_uploaded_file(request.FILES['<name of the FileField in models.py>'])

def handle_uploaded_file(f):
    dest = open('/path/to/file', 'wb') # write should overwrite the file
    for chunk in f.chunks():
        dest.write(chunk)
    dest.close()

check here: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ If that doesn't work, I suppose you could just use os.system to delete the file if the form is accepted. That probably wouldn't be that great of a solution, but it should work.

like image 74
randrumree Avatar answered Sep 21 '22 22:09

randrumree