使用Django ModelForm上传配置文件图像 [英] Uploading Profile Image using Django ModelForm
问题描述
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})
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屋!