django基础使用
//创建应用 python3 manage.py startapp mysite //开启服务 python3 manage.py runserver 127.0.0.1:8080 //创建数据库命令 python3 manage.py makemigrations python3 manage.py migrate //正则表达式 import re ret=re.search('(?P<id>\d{3})/(? P<name>\w{3})','weeew34ttt123/ooo') print(ret.group()) print(ret.group('id')) print(ret.group('name')) //r 表示原生字符串 , ^表示以它为开头, &表示以此结束 url(r'^userInfor/&', views.userInfor) //使用()获取url中的参数,参数位置顺序必须和URL中前后一致 re_path(r'articles/([0-9]{4})/([0-9]{2})', views.year_archive) def year_archive(request, yearParam, monthParam): return HttpResponse(yearParam + " year " + monthParam + " month ") //给url中的参数命名,方法调用时,顺序可以不一致 url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.name_archive), def name_archive(request, month, year): return HttpResponse(year + " year " + month + " month ")
//url中添加参数,前端form表单中action使用别名({% url "James" %})指向url,后端修改url不影响前端 re_path(r'login/', views.login, name="James") re_path(r'pay/login/', views.login, name="James") <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action={% url "James" %} method="post"> <input type="text" name="userName"> <input type="password" name="password"> <input type="submit" name="submit"> </form> </body> </html> def login(request): if request.method == "POST": name = request.POST.get("userName") pwd = request.POST.get("password") if name == "James" and pwd == "123": return HttpResponse("登录成功") return render(request, "name.html")
如果action为空,还走当前url
//项目url,映射到子模块,查找url from django.contrib import admin from django.urls import path,re_path,include from blog import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^blog', include('blog.urls')), ] //具体某些模块url from django.contrib import admin from django.urls import path,re_path,include from blog import views urlpatterns = [ re_path(r'news/story/$', views.introduce) # path('news/story/', views.introduce) ]
posted on 2019-03-18 16:39 JieFangZhe 阅读(94) 评论(0) 编辑 收藏 举报