【问题标题】:How to get an ImageField URL within a template?如何在模板中获取 ImageField URL?
【发布时间】:2012-01-13 12:24:07
【问题描述】:

我的 Django 应用中有以下模型:

class Image(models.Model):
    image = models.ImageField(
        upload_to='images/', 
        height_field='height', 
        width_field='width'
    )
    credit = models.CharField(max_length=50, blank=True)
    caption = models.TextField(blank=True)
    article = models.ForeignKey(Article)
    width = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False,
        default = 0
    )
    height = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False,
        default = 0
    )

我已将 MEDIA_ROOT 设置为我的 Apache Web 根目录中名为 /hmedia/ 的目录,并将 MEDIA_URL 设置为 'http://localhost/hmedia/'。这似乎奏效了——我已经通过 Django 管理站点成功上传了几张图片,我可以通过http://localhost/hmedia/images/[filename] 查看这些图片。 Django 管理站点实际上向我显示了文件名,以及指向每个图像的实时 URL 的链接,并且这些链接有效。

我的问题是,我不知道如何在我的模板中获取这些图像的 URL 或文件名:

<ul>
{% for image in article.image_set.all %}
    <li>Caption: "{{image.caption}}", Credit: "{{image.credit}}", URL: "{{image.url}}"</li>
{% endfor %}
</ul>

上面的模板结果如下:

<ul>

    <li>Caption: "here's an image caption", Credit: "some photographer", URL: ""</li>

    <li>Caption: "Another caption here", Credit: "Another photographer", URL: ""</li>

</ul>

换句话说,它正确地输出了每张图像的标题和信用属性,但它没有为 {{image.url}} 输出任何内容。

如何在模板中获取图片的 URL? Django 管理界面模板是如何做到的? (我已经在管理模板目录中找到了根,但找不到我要找的东西。)

【问题讨论】:

  • 您只需要访问图像字段本身的 .path 和 .url - 所以 image.image.pathimage.image.url。照原样,您正在尝试访问模型实例上不存在的那些属性。

标签: python django


【解决方案1】:

您需要的是{{ image.image.url }}{{ image.image.path }},而{{ image }} - 只是一个图像对象,定义模型的实例和{{ image.image }} 将我们带到ImageField 对象的字段并提供所有指定的属性。

【讨论】:

    【解决方案2】:

    将您的代码更改为:

    <ul>
    {% for image in article.image_set.all %}
        <li>Caption: "{{ image.caption }}", Credit: "{{ image.credit }}", URL: "<a href ='/{{ image.image }}'{{ image.image }}</a>"</li>
    {% endfor %}
    </ul>
    

    将 {{ image.url }} 更改为 {{ image.image }} 因为 '.image' 包含图像的位置。您没有从 '.url' 获得任何价值的原因是您的模型中的类 Image 中没有字段 url。

    【讨论】:

      【解决方案3】:

      如果您在 forms.py 中有 ImageForm 并将 Form Instance 传递给您的 django 模板 那么 src="{% get_media_prefix %}{{your-form-instance.instance.image}}" 将解决您的问题。

      models.py

      class Addon(models.Model):
          image = models.FileField(upload_to='addons/', null=True)
          addon_name = models.CharField(max_length=100, null=False, blank=False)
      

      forms.py

      class AddonForm(forms.ModelForm):
          addon_name = forms.CharField(max_length=100, required=True)
          image = forms.ImageField(required=False)
      

      views.py

      @require_http_methods(['GET'])
      def addons(request, ):
          addon_form_set = modelformset_factory(Addon, form=AddonForm, extra=1)
          addon_forms = addon_form_set(queryset=Addon.objects.all())
          return render(request, 'addons/addons.html', {'form': addon_forms)
      

      your_templates.html

      {% for data in form %}
         <img src="{% get_media_prefix %}{{data.instance.image}}"/>
      {% endfor %}
      

      【讨论】:

        【解决方案4】:

        在您的 django 项目中创建一个“静态”文件夹并将其添加到您的设置文件中

        STATICFILES_DIRS = (
            os.path.join(BASE_DIR, 'static'),
        )
        

        如果你的设置文件中没有这一行,也添加它

        BASE_DIR = os.path.dirname(os.path.dirname(__file__))
        

        现在你可以在模板中使用

        {% static  image.image.url %}
        

        【讨论】:

        • 这个不行,因为图片字段字段和静态文件没有关系!!
        • 这是关于模型对象的问题,而不是静态文件
        猜你喜欢
        • 2018-10-16
        • 2013-03-23
        • 1970-01-01
        • 2015-01-11
        • 2023-03-18
        • 2011-02-22
        相关资源
        最近更新 更多