1)在models.py中:
class SeekerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#other fields
photo = models.ImageField(upload_to='images/', null=True, blank=True)
2)在views.py
中@login_required
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
@login_required
def seeker_profile_update (request,template_name ='munichlivingapp / seeker_myprofile_edit.html'):
logged_in_type = "Seeker"
u = User.objects.get(username=request.user)
seeker_obj = SeekerProfile.objects.get(user=u)
usereditform = UserEditForm(request.POST or None, instance=u)
seekerprofileeditform = SeekerProfileEditForm(request.POST or None, request.FILES or None, instance=u.seekerprofile)
if request.method == 'POST':
if usereditform.is_valid():
user = usereditform.save()
seekerprofileeditform_aux = SeekerProfileEditForm(data=request.POST, files=request.FILES)
if seekerprofileeditform_aux.is_valid() and 'photo' in request.FILES:
seeker_obj.photo.delete()
seeker_obj.save()
if seekerprofileeditform.is_valid():
if 'photo' in request.FILES:
handle_uploaded_file(seeker_obj.photo)
seeker_obj.save()
return redirect('seeker_myprofile')
else:
return render(request, template_name, {'usereditform': usereditform, 'seekerprofileeditform': seekerprofileeditform, 'logged_in_type': logged_in_type })
上面的代码有效,该模板呈现无错误。由于某些原因,图像文件永远不会保存。