python路由分发应用app路由关系

django-admin startproject demo02 #创建工程
cd demo02

#设置工程 demo02 总路 urls.py 由分发,至app应用下路由urls

python manage.py startapp xtt    #创建应用
进入web1 创建 urls.py

编辑xtt应用下的urls.py           #编辑应用下的urls
from django.urls import re_path
from django.shortcuts import HttpResponse

from xtt import views

urlpatterns = [
    re_path('sub/', views.sub )
]

编辑xtt应用下的views.py          #编辑应用下的views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
def sub(request):
dic = {"xuesheng" : "xiaoming", "nianing":27,}
return HttpResponse(dic.items())

编辑demo02项目下的setting.py,将新建应用xtt,添加进去
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'xap',
    'xtt',
]


编辑demo02项目下的urls.py,将总路由,分发至各个应用下xtt的urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('xap/', include("xap.urls")),
    path('xtt/', include("xtt.urls")),
]

python manage.py runserver        #启动应用

- - - - - - - 此处简单的python项目,已启动,可以测试了 - - - - - - - - - - - - 

后续 ...,导入html


在与settings.py同级目录下的__init__.py中引入模块和进行配置,用于加载数据库驱动
import pymysql
pymysql.install_as_MySQLdb()


# 设置html,数据与图片静态分离
在demo2项目下,新建templates的python包,并创建各个一个用对应的html

编辑demo02项目下的setting.py,将DIRS的[],添加'DIRS': [os.path.join(BASE_DIR, 'templates')],

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

现在开始编写 xtt应用的 views.py ,通过render函数,把数据渲染到 html 上

'''
from django.shortcuts import render
from django.shortcuts import HttpResponse
def sub(request):
    dic = {"xuesheng" : "xiaoming", "nianing":27,}
    return HttpResponse(dic.items())
'''

#字典获取方式
from django.shortcuts import render


def sub(request):
    context = {}
    context['hello'] = 'Hello World!'
    return render(request, 'xtt.html', context)


修改 templates下的 xtt.html, 主要是获取 { { hello }}数据


#字符串获取方式

views.py中

from django.shortcuts import render

def sub(request):
    str = "xuesheng"
    return  render(request, 'xtt.html', {"str":str})

xxt.html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>xtt数据</title>
</head>
<body>
   <p> { { str }} </p>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zhiboqingyun/article/details/113118553