Django框架的使用教程--視圖和路由[二]
阿新 • • 發佈:2018-06-30
test turn ssa IV fig tin IE charset doc
視圖和路由
1.創建一個django_test應用
2.setting中設置django_test
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘django_test.apps.DjangoTestConfig‘ ]
3.在django_test中的view.py中寫視圖函數
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse(‘歡迎來到Gaidy博客‘)
4.django_test中創建一個urls.py文件用來關聯Django目錄下的urls.py
from django.conf.urls import url from. import views urlpatterns = [ # 這邊定義子應用的路由 url(r‘index/$‘,views.index) ]
5.Django目錄下的urls.py的設置
from django.conf.urls import url,include from django.contrib import admin import django_test.urls urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘‘,include(django_test.urls)) ]
6.運行程序
返回html頁面
1.在templates創建一個index.html頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gaidy</title> </head> <body> 這是一個頁面 </body> </html>
2.views.py視圖函數修改
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, ‘index.html‘) # return HttpResponse(‘歡迎來到Gaidy博客‘)
3.運行結果
視圖模板
1.前端頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gaidy</title> </head> <body> {{ string }} </body> </html>
2.修改view.py代碼
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render def index(request): date = "我是來自北方的一條狼" return render(request, ‘index.html‘, {"string":date}) # return HttpResponse(‘歡迎來到Gaidy博客‘)
3.運行結果
Django框架的使用教程--視圖和路由[二]