我正在创建一个设置页面,用户应该可以在其中更改图像和生物数据。但是当我打印 request.FILES.GET("profile_picture") 时,只有生物数据会更新,它会打印我上传的照片的名称。为什么没有上传并保存到数据库?
模型.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
profile_pic = models.ImageField(upload_to="images/", null=True ,blank=True)
bio = models.TextField(max_length=100, blank=True)
表格.py
class ProfileForm(forms.Form):
profile_picture = forms.ImageField(required=False )
bio = forms.CharField(label='Bio', max_length=100 ,widget=forms.Textarea())
视图.py
def settings(request):
if request.user.is_authenticated:
intial_data = {
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'user_name': request.user.username,
'email':request.user.email,
'bio':request.user.bio
}
profile_form=ProfileForm(intial_data)
if request.method == "POST":
profile_form=ProfileForm(request.POST, request.FILES)
if profile_form.is_valid():
user_name = profile_form.cleaned_data.get('user_name')
profile_picture =request.FILES.get('profile_picture')
bio = profile_form.cleaned_data.get('bio')
user= User.objects.get(pk=request.user.id)
if user is not None:
user.profile_picture=profile_picture
user.bio=bio
user.save()
context ={
"profile_form":profile_form
}
return render(request, 'user/settings.html',context)
return redirect('home')
my_template.html
<tr>
<td>Bio</td>
<td>{{profile_form.bio}}</td>
</tr>
<tr>
<td>Update Profile Picture</td>
<td>{{profile_form.profile_picture}}</td>
</tr>