使用Django ModelForm上传Profile Image

时间:2011-08-31 16:34:25

标签: django file-upload modelform

我已经查看过相关问题,但没有一个答案似乎有效。我正在尝试为用户上传个人资料图片,并让它替换(覆盖)当前图像。保存图像后,我想将文件名更改为用户ID。在当前形式中,图像将上传,但不会替换现有图像(例如,它将保存为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 个答案:

答案 0 :(得分:5)

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

点击此处:https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ 如果这不起作用,我想如果表单被接受,我可以使用os.system删除文件。这可能不是一个很好的解决方案,但它应该有效。