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

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

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 %}

即使检查页面,我也会得到以下信息:

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

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

from django.conf.urls.static import static

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

仍然没有运气

yangbei1024 回答:在模板标记Django Python中处理媒体图像时出错

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

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

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

,

尝试使用:

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

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

本文链接:https://www.f2er.com/2917245.html

大家都在问