我可以上传个人资料图片并将其发送到数据库。我的views.py中有一个“print(profile.profile_picture)”,当我保存时,它会在控制台中正确打印当前的个人资料图片。由于某种原因,个人资料图片不会显示,我的 profile.html 中的“{% if profile.profile_picture %}”甚至没有拾取任何内容。 []
观点.PY=
@login_required
def profile(request):
profile, created = Profile.objects.get_or_create(user=request.user)
print(profile.profile_picture)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('base:profile') # Redirect to the home page after form submission
else:
form = ProfileForm(instance=profile)
return render(request, 'profile.html', {'form': form})
简介.HTML=
<div class="ProfilePage">
<form method="POST" enctype="multipart/form-data" class="profile-form">
{% csrf_token %}
<div class="form-group">
<label for="id_username">Username:</label>
<input type="text" id="id_username" value="{{ request.user.username }}" readonly>
</div>
<div class="form-group">
<label for="id_bio">Bio:</label>
<textarea id="id_bio" name="bio" rows="4" cols="50" required>{{ form.bio.value }} </textarea>
</div>
<div class="form-group">
<label for="id_profile_picture">Profile Picture:</label>
<input type="file" id="id_profile_picture" name="profile_picture" accept="image/*">
</div>
{% if profile.profile_picture %}
<div class="form-group">
<label>Profile Picture Preview:</label><br>
<img src="{{ profile.profile_picture.url }}" alt="Profile Picture" style="max-width: 500px;">
</div>
{% endif %}
<button type="submit" class="btn-submit">Save</button>
</form>
</div>
表格.PY=
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['bio', 'profile_picture']
我可以提供更多信息,我有点困惑为什么这不起作用。
您是否已将这些代码行尾添加到项目设置文件夹中的 urls.py 中
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)