【问题标题】:{%static %} the page displays the line itself {%load static %} instead of loading the desired file{%static %} 页面显示行本身 {%load static %} 而不是加载所需的文件
【发布时间】:2023-02-25 03:47:31
【问题描述】:

我想将一个 css 文件连接到这个 html 文件,我想通过 {%load struct%} 添加它

`{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
    <title>Brewtopia Cafe form</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{% static 'css/style_contact.css' %}">
</head>
<body>
<header>`

这是应用程序中的 urls.py

`from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', views.Brewtopia_view, name='brewtopia'),
    path('Contact/', views.Contact_view, name='contact')
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
`

这些是应用程序中的 views.py

`from django.shortcuts import render


def Brewtopia_view(request):
    return render(request, 'Brewtopia.html')


def Contact_view(request):
    return render(request, 'Contact.html')
`

settings.py 静态设置

`STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / "static",
]`

css 文件位于文件夹 C:\Projects\brew\brewtopia\users\static\users\css

我添加了struct,想上传一个css文件,但是错误在截图中 enter image description here 但即使你删除 {%loadstruct%} 它也不会工作

【问题讨论】:

    标签: python html css django


    【解决方案1】:

    在 views.py 中,需要导入模板渲染器:

    from django.template import loader
    from django.http import HttpResponse
    

    然后,在您的每个视图函数中,您返回如下内容:

    def view_name(request) -> HttpResponse:
        template = loader.get_template('module_name/Brewtopia.html')
        context = {} # variables you use in your template go here- read the reference at the end for more info
    
        return HttpResponse(template.render(context, request))
    

    不要忘记用“module_name”代替应用程序的名称。

    这是一个使用模板的相当不错的例子: https://docs.djangoproject.com/en/4.1/intro/tutorial03

    这有一些更深入的信息: https://docs.djangoproject.com/en/4.1/topics/templates/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-03
      • 2016-03-29
      • 2020-04-06
      • 2011-08-04
      • 2018-11-16
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      相关资源
      最近更新 更多