首页 > 代码库 > 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中定义的函数 ]
动态路由:
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 !
命名参数:
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)
额外参数:
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))
启动服务
python manage.py runserver localhost:8888
Python3-Django-1.开发环境搭建
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。