django的安裝參照其他教程。
版權聲明:本文爲CSDN博主「stu_xujin」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/xujin0/article/details/83420633
參考上面的項目,只是細化操作步驟,途中遇到一些問題已經修改,參照本文章可以一步一步操作實現。
創建HelloWorld項目:
django-admin startproject HelloWorld
上面即創建了一個django HelloWorld項目。
manage.py |
#!/usr/bin/env python import os import sys
if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "HelloWorld.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
|
__init__.py文件爲空 |
settings.py |
""" Django settings for HelloWorld project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'rhu!76mni$x6f97c!7keq@-+#d_n(ej468dtvs^sb1_(f2^)8q'
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'template_include_demo',
]
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
ROOT_URLCONF = 'HelloWorld.urls'
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [], 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
WSGI_APPLICATION = 'HelloWorld.wsgi.application'
# Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
# Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]
# Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
|
urls.py |
"""HelloWorld URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include
urlpatterns = [ path('admin/', admin.site.urls), path('template/',include('template_include_demo.urls')), ]
|
wsgi.py |
Web服務器網關接口(Python Web Server Gateway Interface,縮寫爲WSGI)是爲Python語言定義的Web服務器和Web應用程序或框架之間的一種簡單而通用的接口。自從WSGI被開發出來以後,許多其它語言中也出現了類似接口。 |
""" WSGI config for HelloWorld project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "HelloWorld.settings")
application = get_wsgi_application()
|
紅色的即爲後期添加的代碼,黑色的爲創建項目後自己生成的代碼。
然後在HelloWorld項目目錄下創建app
template_include_demo
migrations文件夾裏面的__init__.py文件爲空 |
template_include_demo文件夾裏面的__init__.py文件也爲空 |
admin.py |
from django.contrib import admin
# Register your models here.
|
apps.py |
from django.apps import AppConfig
class TemplateIncludeDemoConfig(AppConfig): name = 'template_include_demo'
|
models.py |
from django.db import models
# Create your models here.
|
tests.py |
from django.test import TestCase
# Create your tests here.
|
views.py |
from django.shortcuts import render
# Create your views here. def index(request): return render(request,'template_include.html',{'username':'jason'})
def company(request): return render(request,'company.html')
def school(request): return render(request,'school.html') |
urls.py |
from django.urls import path from . import views
app_name = 'template'
urlpatterns = [ path('',views.index,name='index'), path('company/',views.company,name='company'), path('school/',views.school,name='school'), ]
|
同樣紅色的代碼爲後期添加的。
在新建立的app中,創建一個urls.py的文件,在主urls中對template_include_demo這個app做一層映射,即主urls中添加代碼:
path('template/',include('template_include_demo.urls')),
然後在和app的同級目錄下創建一個templates文件夾,該文件夾裏面新建5個html文件,分別爲template_include.html,company.html,school.html,header.html,footer.html。
然後去views中寫入代碼:
def index(request):
return render(request,'template_include.html',{'username':'jason'})
def company(request):
return render(request,'company.html')
def school(request):
return render(request,'school.html')
在主目錄的settings.py文件中加入代碼:
'DIRS': [os.path.join(BASE_DIR,"templates")],
在INSTALLED_APPS中添加代碼:
'template_include_demo',
在目錄下創建urls.py文件,寫入如下代碼:
from django.urls import path
from . import views
app_name = 'template'
urlpatterns = [
path('',views.index,name='index'),
path('company/',views.company,name='company'),
path('school/',views.school,name='school'),
]
運行django服務器,如下圖所示:
在瀏覽器中輸入網址:
我們可以進行訪問測試,就發現每個頁面只有中間的部分不一樣,而頭部和尾部都是一樣的。這樣我們就能比較方便的編寫每個html文件了。
def index(request):
return render(request,'template_include.html',{'username':'jason'})
可以傳遞字典參數到html頁面,在html頁面只需要寫,即可顯示。
{{ username }}
{{變量}}
{%代碼段落%} 邏輯代碼,如
{%for topic in borad.topics.all%}
{{%topic.subject%}}
{%endfor%}
{%include%} 避免在每個html文件中重寫相同的代碼。
然後我們在header.html中添加一個<li>標籤。
<li>{{ username }}</li>
然後分別在template_include.html,company.html,school.html中的內容下面添加一行代碼。
{{ username }}
我們發現只有首頁中接收到了username這個變量,包括首頁中的header.html也接收到了這個變量,而在company.html和school.html中則沒有接收到username這個變量,包括它們中的header.html都是沒有接收到這個變量的。
所以我們傳入參數至哪個頁面,就只有那個頁面能接收到參數。那麼我們向讓別的頁面也能接收到我們傳入的參數,應該怎樣做呢?
我們只需要在include後面添加一個參數就可以了
在company.html和school.html改變{% include %}標籤中的代碼爲
{% include 'header.html' with username='jason' %}
這樣我們就能在company.html和school.html中接收這個值了。但是,只有header中能接收,在中間部分的div中還是接收不到這個值的。
新建一個front的app,在app下新建一個urls.py的文件,在templates中新建4個html文件,分別爲base.html,company_front.html,index_front.html,school_front.html。然後將此app註冊到settings.py的文件中。
在新建的front app views.py中添加。
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index_front.html')
def company(request):
return render(request,'company_front.html')
def school(request):
return render(request,'school_front.html')
然後添加映射,首先先將此app在主urls中做一層映射
path('front/',include('front.urls')),
然後在此app中的urls中添加映射from django.urls import path
from . import views
app_name = 'front'
urlpatterns = [
path('',views.index),
path('company/',views.company,name = 'company'),
path('school/',views.school,name = 'school'),
]
然後就可以輸入網址進行測試了。
{% extends 'base.html' %}的意思時繼承自base.html,這個裏面有的代碼繼承之後的模板中全部都有。
base.html中的{% block content %}是一個接口,我們可以以在繼承的模板中間使用{% block content %}來改變裏面的代碼。
使用{% block content %}標籤之後,父模板中{% block content %}標籤中的代碼都不會在子模板中顯示出來。(就像上面base.html中的我是父摸版中的代碼從來沒有顯示出來過。)
如果想要父模板中{% block content %}標籤中的代碼顯示出來,則需要添加{{ block.super }}就能夠顯示了。
{% extends 'base.html' %}
{% block content %} {{ block.super }}<br/> 我是主頁代碼 {% endblock %}
|
如果我們在子模板中將代碼放在{% block content %}標籤的外面,Django是不會給我們渲染的,即是沒有效果的。
{% extends 'base.html' %} hello world {% block content %} {{ block.super }}<br/> 我是主頁代碼 {% endblock %}
|
{% extends 'base.html' %}標籤必須是第一個標籤,因此我們一般都是將 {% extends 'base.html' %}放在第一行。
{% extend %}標籤和{% include %}傳參數是一樣的,如果給子模板傳遞了一個參數,那麼該子模板中的父模板能接收到參數,而其他子模板中不能接收到參數。