Django 項目中添加靜態文件夾


在 mysite 文件夾下添加一個 statics 文件夾用來存放 js 文件

在 index.html 文件中添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/userInfo" method="post">
    <p>名字<input type="text" name="username"></p>
    <p>性別<input type="text" name="sex"></p>
    <p>郵箱<input type="text" name="email"></p>
    <p><input type="submit" value="submit"></p>
</form>
<hr>
<h1>數據展示</h1>
<table border="1px">
    <tr>
        <td>名字</td>
        <td>性別</td>
        <td>郵箱</td>
    </tr>

    {% for i in user_list %}
    <tr>
        <td>{{ i.username }}</td>
        <td>{{ i.sex }}</td>
        <td>{{ i.email }}</td>
    </tr>
    {% endfor %}
</table>
</body>
<!-- 新添加 -->
{% load static %}
<script src="{% static "jquery-3.3.1.min.js" %}" ></script>
<script>
    $("h1").css("color","red")
</script>
<!-- 新添加 -->
</html>

在 urls.py 文件中添加

from django.contrib import admin
from django.urls import path
from blog import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('userInfo', views.userInfo),
] + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS)

在 settings.py 中添加

# 在 STATIC_URL = '/static/' 下面添加,STATIC_URL 相當於一個別名,給前端使用,映射 statics 文件夾(該文件夾名字可更改);前端調用就使用 /static/jquery-3.3.1.min.js。與文件夾名字無關。

STATICFILES_DIRS=[
    os.path.join(BASE_DIR, "statics"),
]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM