【问题标题】:Django Default Image is showing显示 Django 默认图像
【发布时间】:2021-01-11 15:52:18
【问题描述】:

为什么我在下面看不到默认图片是我的模型和 profile.html 文件:

型号:

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.ImageField(upload_to='profile_pics',default='default.jpg')

    def __str__(self):
        return f'{self.user.username} Profile'

个人资料.html:

{% extends 'blog/base.html' %}
    {% load crispy_forms_tags %}
    {% block content %}
        <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>
            <!-- FORM HERE -->
        </div>
    {% endblock content %}

提前谢谢你...

【问题讨论】:

  • 您确定您已上传该个人资料的图片吗?看起来路径没问题,如果默认图像显示可能是唯一的情况
  • 那样做可不是个好主意。如果用户有个人资料图片,您应该只签入模板,如果没有显示默认图片。
  • 我已将图像上传到名为 default.jpg 的媒体文件夹。所以我应该为所有用户使用这个默认图片,如果我没有为他们上传特定的图片,但它没有这样做

标签: django django-models django-forms


【解决方案1】:

在模板中,您可以检查图像是否存在,如果不存在,则可以显示静态文件中的默认图像,如下所示

 {% if user.profile.image %}
 <img src="{{ user.profile.image.url }}">
 {% else %}
 <img src="{% static 'img/default.png' %}">
 {% endif %}

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 2011-12-22
    • 2018-05-07
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2012-01-27
    相关资源
    最近更新 更多