传递链接到Django视图中的文件。

huangapple go评论61阅读模式
英文:

How to pass link to file in Django views

问题

以下是代码的翻译部分:

在“task1.html”文件中,你可以这样显示图片:

<figure><img src={% static '{{ main_figure }}' %}></figure>
    
<p>{{ description }}</p>

在“views.py”文件中,你的视图函数如下:

def task1(request):
    return render(
        request,
        "App/Tasks/task1.html",
        {
            'main_figure' : "assets/placeholder_img.png",
            'description' : "Placeholder image and text"
        }
    )

如果图片没有显示,可能是视图函数的问题。你尝试了不同的方式传递图片路径,但都没有成功。希望这有所帮助。

英文:

I am very new to Django and trying display an image on an html page by passing the path to the src from the view.

I have this in the 'task1.html' file

&lt;figure&gt;&lt;img src={% static &#39;{{ main_figure }}&#39; %}&gt;&lt;/figure&gt;
    
&lt;p&gt;{{ description }}&lt;/p&gt;

and this in the 'views.py' file

def task1(request):
    return render(
        request,
        &quot;App/Tasks/task1.html&quot;,
        {
            &#39;main_figure&#39; : &quot;assets/placeholder_img.png&quot;,
            &#39;description&#39; : &quot;Placeholder image and text&quot;
        }
    )

But the image does not show. If I remove the &#39;main_figure&#39; : &quot;assets/placeholder_img.png&quot;, line and change
&lt;figure&gt;&lt;img src={% static &#39;{{ main_figure }}&#39; %}&gt;&lt;/figure&gt;

to &lt;figure&gt;&lt;img src={% static &#39;assets/placeholder_img.png&#39; %}&gt;&lt;/figure&gt;

the image displays, so the issue seems to be with the views function.

I have tried passing different parts of the src from the view, e.g.

&lt;img src={{ main_figure }}&gt;

with &#39;main_figure&#39; : &quot;{% static &#39;assets/placeholder_img.png&#39; %}&quot;,

and

&lt;img src={% static &#39;assets/{{ main_figure }}.png&#39; %}&gt;

with &#39;main_figure&#39; : &quot;placeholder_img&quot;,

but it always shows the little image not found icon.

Any help would be greatly appreciated, thanks very much.

答案1

得分: 1

  1. {{xxx}}只是打印变量xxx(即{{}}中的内容),因此不需要空格。

  2. {% xxx %}执行一个标签,%前后需要空格。

  3. 如果需要在标签内使用变量,不需要使用{{}}:{% static main_figure %}

英文:
  1. {{xxx}} is just printing a variable xxx (so what is inside {{ }}) therefore no spaces are needed.

  2. {% xxx %} is executing a tag and spaces before/after % are necessary

  3. if you need to use a variable inside tag no need to use {{ }}: {% static main_figure %}

huangapple
  • 本文由 发表于 2023年4月6日 19:36:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定