提问人:Melonendk 提问时间:3/6/2018 更新时间:3/6/2018 访问量:745
(姜戈)无法为用户头像上传图像
(Django) Cannot upload images for the users avatar
问:
因此,我试图通过允许用户上传图像来更新他们的头像/个人资料图像 + 我想实现图像裁剪器,以便他们可以将图像裁剪为 1 比 1。我认为第一件事是使上传成为可能。
我四处寻找,试图让它成为可能,但我想我几乎无处不在。
问题是我使用的图像字段就像是 User 表的扩展,我基本上称它为 extendeduser,其中包含所有额外的信息。
媒体设置了 2,我可以从管理面板上传文件,它们正常显示。
Views.py
@login_required
def useravatar(request, user_pk):
if request.method == 'POST':
form = UpdateProfileForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.extendeduser.avatar = form.cleaned_data('avatar')
user.save()
messages.success(request, 'Your avatar was successfully Uploaded!')
return redirect('useravatar', user_pk=request.user.pk)
logged_in_user = get_object_or_404(User, pk=request.user.pk)
requested_user = get_object_or_404(User, pk=user_pk)
driverslicence = DriversLicenceCategories.objects.all()
feedback = FeedbackSupportForm()
password = PasswordChangeForm(request.user)
avatar = UpdateProfileForm(instance=request.user)
context = {
'avatar' : avatar,
'logged_in_user': logged_in_user,
'requested_user': requested_user,
'feedback' : feedback,
'password' : password,
}
return render(request, 'user/avatar.html', context)
Models.py
class ExtendedUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nickname = models.CharField(max_length=20)
birthdate = models.DateField(null=True, blank=True)
postal_code = models.CharField(max_length=10)
phone_number_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+4570131415'. Up to 15 digits allowed.")
phone_number = models.CharField(max_length=16, validators=[phone_number_regex], blank=True)
phone_number_show = models.BooleanField(default=False)
emergency_number = models.CharField(max_length=16, validators=[phone_number_regex], blank=True)
drivers_licence = models.ManyToManyField(DriversLicenceCategories, blank=True)
avatar = models.ImageField(upload_to='users/avatars', default='static/img/userpreload.png')
background = models.ImageField(upload_to='users/backgrounds', default='static/img/userpreload.png')
forms.py
class UpdateProfileForm(forms.ModelForm):
postal_code = forms.CharField(max_length=10, required=True)
phone_number = forms.CharField(max_length=16, required=True)
phone_number_show = forms.BooleanField(required=False)
avatar = forms.ImageField()
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'postal_code', 'phone_number', 'phone_number_show', 'avatar')
当然,还有带有表单的 html 文件
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="custompanel no-m-bottom">
<h3>Avatar</h3>
<hr style="border-color:rgba(0, 0, 0, 1);">
<div class="form-group">
<div class="setting-user-avatar">
<img class="user-avatar" src="{{ logged_in_user.extendeduser.avatar.url }}">
</div>
<label for="id_avatar">Change profile image.</label>
<input id="id_avatar" style="color: #000;" class="victext-input vic-block full-width" type="file" name="avatar"></input>
<small id="id_avatarHelpBlock" class="form-text text-muted">
Current: <a href="{{ logged_in_user.extendeduser.avatar.url }}">{{ logged_in_user.extendeduser.avatar.url }}</a>
</small>
</div>
</div>
<button type="submit" class="vicbtn vicbtn-green w-100">Save</button>
</form>
我希望有人能帮我解决这个问题,因为我基本上完全崩溃了
答:
1赞
Exprator
3/6/2018
#1
试试这个,正如我所认为的那样,您甚至在将图像添加到扩展模型的头像列之前就保存了配置文件
from .models import ExtendedUser
def useravatar(request, user_pk):
if request.method == 'POST':
form = UpdateProfileForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
user = form.save()
av = ExtendedUser.objects.get(user_id=user_pk)
av.avatar = request.FILES['avatar']
// other columns if you want to save, same as above line, except request.FILES will be request.POST['input_name']
av.save()
messages.success(request, 'Your avatar was successfully Uploaded!')
return redirect('useravatar', user_pk=request.user.pk)
并更改您的 HTML
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="custompanel no-m-bottom">
<h3>Avatar</h3>
<hr style="border-color:rgba(0, 0, 0, 1);">
<div class="form-group">
<div class="setting-user-avatar">
<img class="user-avatar" src="{{ logged_in_user.extendeduser.avatar.url }}">
</div>
<label for="id_avatar">Change profile image.</label>
{{ avatar.as_p }}
<small id="id_avatarHelpBlock" class="form-text text-muted">
Current: <a href="{{ logged_in_user.extendeduser.avatar.url }}">{{ logged_in_user.extendeduser.avatar.url }}</a>
</small>
</div>
</div>
<button type="submit" class="vicbtn vicbtn-green w-100">Save</button>
</form>
评论
0赞
Exprator
3/6/2018
您的表单在 HTML 文件中的什么位置??检查 ANS
0赞
Melonendk
3/6/2018
如上所示更改了 HTML。当我提交它指向的地方时,得到“'dict'对象不可调用” - “user.extendeduser.avatar = form.cleaned_data('avatar') ”
0赞
Exprator
3/6/2018
更改了视图部分,只需通过复制粘贴来使用它即可
0赞
Melonendk
3/6/2018
它给出了“MultiValueDictKeyError”
0赞
Exprator
3/6/2018
您必须删除上传头像的旧 HTML 代码,您的 HTML 文件不止一次出现 name=“avatar”,因此存在问题。检查来源,看看你是否多次找到任何 name=“avatar”
2赞
Diksha
3/6/2018
#2
试试这个: 从您的视图中更新此行:
user.extendeduser.avatar = request.FILES['avatar']
评论
0赞
Melonendk
3/6/2018
尝试将其从请求更改为 form.files,依此类推,但出现错误 - “'UpdateProfileForm' 对象没有属性 'FILES'”
0赞
Melonendk
3/6/2018
我们发现了错误,但无论如何感谢您的帮助:)
评论