Django入门

1.在pycham的控制台下载安装Django插件:
pip install django==1.11
下载的是Django的1.11版本,如想安装最新版不用在后添加版本号
pip uninstall django 卸载Django

2.检查安装是否成功
django-admin --version
返回版本号说明安装成功

3.创建第一个django项目
django-admin startproject 项目名
cd 项目名
python manage.py runserver 运行第一个django

4切换语言英文改成中文
settings.py 文件中的 把LANUAGE_CODE='en-us' 改为 LANUAGE_CODE='zh-Hans'

5django路由映射
urls.py
url(r"^index/$",views.index,name="index")

", views.index, name="index") #默认的地址

创建views.py 视图函数的文件
from django.http import HttpResponse
视图函数
def index(request):
return HttpResponse("

页面内容

")

from django.http import HttpResponse

def index(request):
    return HttpResponse("

页面内容

")

扩展:
在Django中创建一个子模块(功能模块)
cd 项目主目录
1、 cd 项目主目录下
django-admin startapp <子模块名称>
2、将子模块注册配置文件中
在根模块的settings.py配置文件中INSTALLED_APPS=["子模块名称"](添加)
3、创建子模块路由(创建uls.py文件)
urls.py,编写对应的路由匹配

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

urlpatterns =[
    url(r"^index/$",views.index, name="index"),
    url(r"^login/$", views.login, name="login"),
    url(r"^register/$", views.register, name="register"),
    url(r"^list/$", views.list, name="list"),
]

4、将子路由交给根路由
在view.py文件中修改为

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

def index(requset):
    print("博客首页")
    return HttpResponse(

博客首页面

) def login(request): return HttpResponse(

用户登录页面

) def register(request): return HttpResponse(

用户注册页面

)

跟模块中的urls.py也进行修改

"""demo_01 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1\. Add an import:  from my_app import views
    2\. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1\. Add an import:  from other_app.views import Home
    2\. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1\. Import the include() function: from django.conf.urls import url, include
    2\. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from . import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'blog/', include("blog.urls")),
    url(r'^blog/', include("blog.urls")),
    # url(r"^index/$", views.index, name="index"),
    url(r"^$", views.index, name="index")
]

你可能感兴趣的:(Django入门)