首页 > 代码库 > Python3-Django-1.开发环境搭建

Python3-Django-1.开发环境搭建

官网

  https://www.djangoproject.com/

安装

  http://www.runoob.com/django/django-install.html

创建项目

  方式一(命令行): django-admin statrproject ProjectName

  方式二(PyCharm): File -> New Project -> Django -> 选择项目路径 -> Create

创建APP

  python manage.py startapp app01

配置URL  

  静态路由:

技术分享
from django.conf.urls import url
from django.contrib import admin
from app01 import views      # 1.导入views模块

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^hello-world/$, views.hello_world),   # 2.配置静态路由,指向views中定义的函数
]
View Code

  动态路由:

技术分享
from django.conf.urls import url
from django.contrib import admin
from app01 import views      # 1.导入views模块

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^hello-to/(\w+)$, views.hello_to),    # 2.配置动态路由,指向views中的函数
]

# 页面访问: http://localhost:8888/hello-to/jack
# 页面响应: Hello,jack !
# 页面访问: http://localhost:8888/hello-to/jet
# 页面响应: Hello,jet !
View Code

     命名参数:

技术分享
from django.conf.urls import url
from django.contrib import admin
from app01 import views      # 1.导入views模块


urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^hello-girl/(?P<girl_name>\w+)$, views.hello_girl),    # 2.hello_girl函数的参数名字,必须是自定义的girl_name
]

# views.py 中的函数
def hello_girl(request, girl_name):
    """
    第一个参数必须是request
    第二个参数是传递的girl_name
    :param request:
    :param girl_name:
    :return:
    """
    return HttpResponse("Hey,Hey,Hey,%s !" % girl_name)
View Code

     额外参数:

技术分享
from django.conf.urls import url
from django.contrib import admin
from app01 import views      # 1.导入views模块

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^hello-extra/(\w+)$, views.hello_extra, {"extra_arg1": "bra1", "extra_arg2": "bra2"}),    # 2.
]
----------------------------------------------------------------------------
# views.py中的函数,额外的参数名称必须保持一致,且要放在最后
def hello_extra(request, arg, extra_arg1, extra_arg2):
    return HttpResponse("Wow,%s %s %s!" % (arg, extra_arg1, extra_arg2))
View Code

 

启动服务

  python manage.py runserver localhost:8888

    

Python3-Django-1.开发环境搭建