使用Django ModelForm上传配置文件图像 [英] Uploading Profile Image using Django ModelForm

查看:213
本文介绍了使用Django ModelForm上传配置文件图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾相关的问题,但没有一个答案似乎工作。我试图上传一个用户的配置文件图像,并取代(覆盖)当前图像。保存图像后,我想将文件名更改为用户标识。在图像上传的当前形式中,它不会取代现有的图像(例如它将被保存为2_1.png)。

  class PhotoForm(forms.ModelForm):
def save(self):
content_type = self。 content_type.split('/')[ - 1]
文件名='%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()
返回实例
$ b $ class Meta:
model = UserProfile
fields =('photo',)
$ b $ def photo_form请求):
如果request.method =='POST':
form = PhotoForm(data = request.POST,file = request.FILES,instance = request.user.get_profile())
如果form.is_valid():
form.save()
else:
form = PhotoForm()
return render(request,'photo_form.html',{'form ':form})


form = PhotoForm(data = request.POST,file = request.FILES,instance = request.user.get_profile())
if form.is_valid():
handle_uploaded_file(request.FILES ['< FileField的名称('/ path / to / file','wb')#write应该覆盖文件
for f.chunks():
dest.write(chunk)
dest.close()

请点击此处: https:// docs.djangoproject.com/en/dev/topics/http/file-uploads/
如果这不起作用,我想你可以使用os.system删除文件,如果窗体是公认。这可能不是一个伟大的解决方案,但它应该工作。


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

解决方案

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.

这篇关于使用Django ModelForm上传配置文件图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆