在模板模板标记Django Python中处理媒体图像时发生错误

问题描述 投票:0回答:2

我觉得我正在忽略一些小东西,但是我试图使用模板标记显示上传的服装文件的媒体文件:

INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'apparelapp',
    'import_export',
]

settings.py

MEDIA_DIR = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
MEDIA_ROOT = "MEDIA_DIR"

models.py

class Uniform(models.Model):
    category = models.CharField(choices = CATEGORY_CHOICES, max_length=11)
    description = models.CharField(max_length = 50)
    price = models.FloatField(max_length = 6)
    size = models.CharField(choices=CLOTHES_SIZE, max_length=4, blank=True)
    style = models.CharField(choices=STYLE_CHOICES, max_length=15, blank=True)
    image = models.ImageField(upload_to='uniforms/')

html

  <div class="row wow fadeIn">
    {% for item in uniform %}
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card">
                <div class="view overlay">
                    <img src="{{ item.image.url }}" alt="Oh no!">
                    <a>
                        <div class="mask rgba-white-slight"></div>
                    </a>
                </div>
                <div class="card-body text-center">
                    <label>
                        <h5>{{ item.description }}</h5>
                    </label>
                    <h5>
                        {% if item.description %}
                        <strong>
                            <label for="">{{ item.category }}</label>
                        </strong>
                    </h5>
                    {% endif %}
                </div>
            </div>
        </div>
    {% endfor %}

即使检查页面我也得到以下信息:image url inspection

该路径对我来说都是正确的,即使是settings.py模型的image设置并上传的Uniform对象路径也是如此。我想念什么吗?我查看了其他一些帖子,并在urls.py中看到了一个建议,其中包括:

from django.conf.urls.static import static

urlpatterns = [
...
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

仍然没有运气

python django media
2个回答
0
投票

我认为您必须确保完成所有这些步骤:

  • “ django.contrib.staticfiles”包含在您的INSTALLED_APPS中
  • 在您的设置STATIC_URL = '/static/'中定义STATIC_URL
  • 在模板中使用{% load staticfiles %}

为确保其正常工作:尝试打开 http:localhost:8000 / static / media / your_image.png您应该只看到图像。


0
投票

尝试使用:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

没有MEDIA_DIR(与STATICFILES_DIRS不同,并且您还应该将MEDIA_ROOT设置为字符串,而不是列表。

© www.soinside.com 2019 - 2024. All rights reserved.