Django系列2:MTV简单流程

1、模板使用方式1:在App目录下建立templates文件夹

views.py

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.


def hello(request):

    return HttpResponse("views中的hello函数返回Hello")


def index(request):

    return render(request, "index.html")

urls.py

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

from App import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.hello),
    path('index/', views.index),

]


settings.py

# Application definition
# django开头的为Django内置的应用
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'App'
]


2、模板使用方式2:在项目目录下建立templates文件夹

settings.py

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

views.py

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.


def hello(request):

    return HttpResponse("views中的hello函数返回Hello")


def index(request):

    return render(request, "index.html")


def home(request):

    return render(request, "home.html")

urls.py

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

from App import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.hello),
    path('index/', views.index),

    path('home/', views.home),

]

3、Project下建立多App路由使用

1) python manage.py startapp Two

工程下建立Two的App

2)settings.py注册Two

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'App',
    'Two'
]

3) Two 下建立urls.py

from django.conf.urls import url
from Two import views

urlpatterns = [
    url('index/', views.index),
]

4) 工程下urls (include)

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

from App import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.hello),
    path('index/', views.index),

    path('home/', views.home),

    path('two/', include('Two.urls')),

]

posted @ 2020-01-21 16:04  xidianzxm  阅读(245)  评论(0编辑  收藏  举报