提问人:DoTech J 提问时间:11/13/2023 最后编辑:DoTech J 更新时间:11/13/2023 访问量:24
当前 URL 锚链接从 Django 表单模型 ImageField 添加到我的 Tempalte
Current URL anchor link gets added to my Tempalte from Django Form Model ImageField
问:
我创建了一个 UserProfile。面临有关 ImageField 的问题。我在前端一切正常,直到我将图像从管理员添加到我的用户配置文件中以对其进行测试。我得到的是锚链接,它是我的用户个人资料的当前 URL,而不是获取图片。
我需要帮助!!
models.py
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from PIL import Image
# Create your models here.
class Profile(models.Model):
slug = models.SlugField(max_length=255, unique=True, null=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField('profile picture', default='accounts/avatars/default_avatar.jpg', upload_to="accounts/avatars/")
bio = models.TextField(max_length=500, null=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.slug = slugify(self.user.get_username())
super().save(*args, **kwargs)
img = Image.open(self.avatar.path) # Open image
# resize image
if img.height > 150 or img.width > 150:
output_size = (150, 150)
img.thumbnail(output_size) # Resize image
img.save(self.avatar.path) # Save it again and override the larger image
views.py
@login_required
def profile(request):
if request.method == 'POST':
p_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
if p_form.is_valid():
p_form.save()
messages.success(request, f'Your profile has been updated!')
return redirect('home') # Redirect back to home page
else:
p_form = UpdateProfileForm(instance=request.user.profile)
print(p_form.fields)
context = {
'p_form': p_form
}
return render(request, 'accounts/profile.html', context)
配置文件.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="profile-pic-wrapper">
<div class="pic-holder">
<!-- uploaded pic here -->
<img id="profilePic" class="pic" src="{{ user.profile.avatar.url }}">
{% render_field p_form.avatar|attr:'id:newProfilePhoto' class+="uploadProfileInput form-control-file mb-3" %}
<label for="newProfilePhoto" class="upload-file-block">
<div class="text-center">
<div class="mb-2">
<i class="fa fa-camera fa-2x"></i>
</div>
<div class="text-uppercase">
Upload <br /> Profile Photo
</div>
</div>
</label>
</div>
</div>
{% render_field p_form.bio class+="form-control mb-3" placeholder="Bio..." %}
<div class="text-center">
<button type="submit" class="btn btn-primary btn-block mx-auto">
Next<i class="fa fa-solid fa-right-long ms-2"></i>
</button>
</div>
</form>
我花了一整天的时间解决并尝试解决它的方法,我可以但没有找到解决方案。
每当我重新加载页面时,它都会添加此额外代码。
'“当前:” accounts/avatars/107178_circle_LinkedIn_icon.png
“更改: ”
请帮忙!!
我也想分享我想要在我的头像中显示当前的 URL 图像。当我删除所有内容并放置 .{{ form_p.avatar }}
`
答: 暂无答案
评论