Django 多app路由分发
Harold_96_lxw 人气:01、环境搭建
Python3.6.7
pip install django==2.2.6
2、生成django项目
django-admin startproject yourproject
3、创建app
python manage.py startapp app1 python manage.py startapp app2
需要将app注册到项目的settings.py中
4、在每个app下创建templates文件夹,用于创建html页面
5、每个app创建urls.py用于构建每个app的分路由
重点关注name声明
from django.urls import path from . import views urlpatterns=[ path('search/',views.search,name='diary_search'), path('home/',views.home), ]
6、项目总路由urls.py
重点关注include写法、namespace声明
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('skynet/', include(('skynet.urls','skynet'),namespace='skyent')), path('diary/', include(('diary.urls','diary'),namespace='diary')), ]
7、每个app的前端页面
重点关注form action
<form action="{% url 'skynet:skynet_search'%}" method="post"> {% csrf_token %} <input type="text" name="keywords"> <button type="submit">提交</button> </form>
8、每个app的view.py
from django.shortcuts import render #Create your views here. def home(request): return render(request,'index.html') def search(request): keywords=request.POST.get('keywords') print(keywords) return render(request,'index.html')
总结:经过上述操作可实现django项目多app路由分发,这样做的好处是只需要修改后端路由,前端的路由会随之变化
加载全部内容