欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django实现动态路由的简单方法

程序员文章站 2024-02-15 19:22:47
...

使用django的时候需要配置路由

需要在url中进行路由配置,很麻烦、
path(‘new/’, include(‘newxichentousystem.urls’)),

关键还有再配置子路由,也很麻烦

这样做的好处

整个项目只需要有一个url.py 文件即可

根据请求名,调用函数

from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include,re_path
from django.views.static import serve

from django10 import settings
from villagemanage import views as views1
from newxichentousystem import views as views2

from dongtailuyou import views as views3
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views1.index, name='index'),
    re_path(r'^dturl/(?P<fucname>[a-zA-Z0-9]+)/$',views3.usefucbyname),
    url(r'^media/(?P<path>.*)', serve, {"document_root":settings.MEDIA_ROOT}),

]

在app.view文件中

放在页面开头就好

def usefucbyname(request,fucname):
    return eval(fucname)(request)

别忘了记得在django.setting 中添加app名称

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'villagemanage',
    'newxichentousystem',
    'dongtailuyou'
]

ajax 携带口令

$.ajaxSetup({
data: {csrfmiddlewaretoken: ‘{{ csrf_token }}’ },
});

相关标签: 动态路由