从静态文件夹 - Django将图像添加到django模板中

时间:2017-10-06 09:18:25

标签: django django-templates

我有一个Django模板,我想从我在应用程序中的静态文件夹中添加一个静态图像到该文件。 我正在尝试但模板上没有出现任何内容。

有谁知道我的错误来自哪里?

这是我的代码:

{% extends "base.html" %}

{% block content %}
<div class="row">
  <div class="col">
    <img src="static/images/Artboard1.png" alt="">
    <h2>{{ currentUser.username }}</h2>
  </div>

  <a href="{% url 'logout' %}">Logout</a>
{% endblock %}

以下是我的目录的图片:

enter image description here

3 个答案:

答案 0 :(得分:5)

扩展之后

staticfiles 标记加载到模板

{% extends "base.html" %}
{% load staticfiles %}

然后在 img HTML标记 src 属性中使用它

<img src="{% static 'images/Artboard1.png'%}" alt="">

答案 1 :(得分:3)

在setting.py中配置以下设置

STATIC_ROOT = os.path.join(BASE_DIR,"static_files")
STATIC_URL = '/static/'

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

并在您的模板中使用

<img src="{% static 'images/Artboard1.png'%}" alt="">

希望这对你有帮助

答案 2 :(得分:0)

我有同样的问题。我通过在每个子页面中添加def register(request): if not request.user.is_authenticated: # The correct way to test for logged in user if request.method == "POST": form = UserRegisterForm(request.POST) form1 = AddressRegisterForm(request.POST) if form.is_valid() and form1.is_valid(): email = form.cleaned_data.get("email") if not User.objects.filter(email=email).exists(): username = form.cleaned_data.get("username") messages.success( request, f"The Account created for {username}! You are now able to login.", ) user = form.save() profile = user.profile profile.mobile_number = form.cleaned_data['mobile_number'] address = form1.save() profile.address = address profile.save() return redirect("login") else: messages.warning( request, f"The email is either invalid or already used to create an account", ) else: form1 = AddressRegisterForm() form = UserRegisterForm() return render(request, "register.html", {"form": form, "form1": form1}) else: username = request.user.username messages.warning(request, f"You are already logged in as {username}!") return redirect("home") 来解决该问题。

喜欢这里:

{% load static %}