Uploading Profile Image using Django ModelForm

2019-04-08 09:11发布

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})

1条回答
Ridiculous、
2楼-- · 2019-04-08 10:07
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.

查看更多
登录 后发表回答