我的 models.py 中有 Profile 类:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to=path_and_rename)
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
和 ProfileUpdateForm,用于编辑个人资料,在我的 forms.py 中:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
我将 ProfileUpdateForm 作为上下文(p_form)传递到我的 html 文件并用脆皮显示它:
个人资料.html
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="post">
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Update Profile</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit"> Update </button>
<a class="btn btn-outline-danger" href="{% url 'user-delete' user.id %}">Delete Profile</a>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">Already Have an Account?
<a href="{% url 'login' %}" class="ml-2">Sign In</a>
</small>
</div>
</div>
{% endblock body %}
所有个人资料都有图像,所以我显示 u_form(UserUpdateForm,用于用户名和电子邮件更新),然后显示 p_form(ProfileUpdateForm)
选择图像时,仅显示文件名。
当用户在表单中选择图像时,我希望图像显示在/而不是其名称旁边,有没有办法做到这一点?
Django 本身无法帮助你。你必须使用Javascript来实现你的愿望。有很多库可以为你做到这一点,但是你可以不使用库而仅使用JS来实现你想要的。检查这个问题的答案