赞
踩
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 %}传参数是一样的,如果给子模板传递了一个参数,那么该子模板中的父模板能接收到参数,而其他子模板中不能接收到参数。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。