Python3-Django-1.开发环境搭建
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.开发环境搭建的主要内容,如果未能解决你的问题,请参考以下文章