Django学习(一)
簡(jiǎn)介:
Django是python的web開(kāi)發(fā)框架之一
Django的安裝:
(略)
創(chuàng)建Django項(xiàng)目(一個(gè)Django項(xiàng)目可以包含多個(gè)app):
使用命令:
django-admin startproject mysite
這樣就創(chuàng)建了好了一個(gè)香名為:mysite 的項(xiàng)目;目錄如下:
mysite/manage.pymysite/__init__.pysettings.pyurls.pywsgi.py 創(chuàng)建Django ?app: python manage.py startapp myApp 這樣就創(chuàng)建了一個(gè)名為:myApp的應(yīng)用,目錄結(jié)構(gòu)為: myApp/__init__.pyadmin.pymigrations/__init__.pymodels.pytests.pyviews.py 配置App到項(xiàng)目中:打開(kāi)mysite/setting.py ;進(jìn)行如下設(shè)置:
INSTALLED_APPS = ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','myApp', ) 這樣就在項(xiàng)目中添加了myApp這個(gè)應(yīng)用定義視圖函數(shù):
編輯myApp/views.py,加入如下代碼:
#coding:utf-8 #coding:utf-8 from django.http import HttpResponse from django.shortcuts import render_to_response# Create your views here.def index(request):return HttpResponse(u"歡迎光臨!")然后再配置,mysite/mystie/utls.py 文件: from django.conf.urls import include, url from django.contrib import admin from myApp.views import *urlpatterns = [url(r'^admin/', include(admin.site.urls)),url(r'^index/$',index), ] 或者: from django.conf.urls import include, url from django.contrib import adminurlpatterns = [url(r'^admin/', include(admin.site.urls)),url(r'^index/$','myApp.views.index'), ]回到項(xiàng)目的根目錄:/mysite ,啟動(dòng)應(yīng)用: python manage.py runserver 192.168.1.111:8000 ip地址根據(jù)本機(jī)地址設(shè)置,這樣就啟動(dòng)了一個(gè)應(yīng)用,訪問(wèn)192.168.1.111:8000/index ,即可看到我們剛才編寫(xiě)的頁(yè)面
定義模板視圖:
在myApp目錄下下面創(chuàng)建一個(gè)目錄:templates,用于存放html網(wǎng)頁(yè)
編寫(xiě)好一個(gè)網(wǎng)頁(yè)文件 hello.html
配置模板目錄的路徑,打開(kāi)mysite/setting.py,移動(dòng)到最后,添加一下代碼:
STATIC_URL = '/static/' import os TEMPLATE_DIRS = [os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'), ]這樣就配置好了模板路徑
添加訪問(wèn)模板的函數(shù);打開(kāi)myApp/views.py,添加一個(gè)函數(shù)hello:
#coding:utf-8 from django.http import HttpResponse from django.shortcuts import render_to_response# Create your views here.def index(request):return HttpResponse(u"歡迎光臨!")def hello(request):return render_to_response('hello.html') 定義視圖相關(guān)的url,打開(kāi)mysite/setting.py,配置如下: from django.conf.urls import include, url from django.contrib import adminurlpatterns = [url(r'^admin/', include(admin.site.urls)),url(r'^index/$','myApp.views.index'),url(r'^hello$','myApp.views.hello'), ]保存,并訪問(wèn)192.168.1.111:8000/hello ;就可以訪問(wèn)到hello.html這個(gè)網(wǎng)頁(yè)了。
參考地址:
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
http://www.ziqiangxuetang.com/django/django-views-urls.html
總結(jié)
以上是生活随笔為你收集整理的Django学习(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python 关闭 os.popen()
- 下一篇: 解决fragment replace