亲宝软件园·资讯

展开

Django多个app urls配置代码实例

-零 人气:0

快速测试创建项目与app

django-admin startproject mysite
django-admin startapp app1
django-admin startapp app2

mysite下的urls.py文件

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
  path('admin/', admin.site.urls),
  path('app1/', include('apps.app1.urls',namespace='app1')),
  path('app2/', include('apps.app2.urls',namespace= 'app2')),
]

app1下的apps文件

from django.apps import AppConfig
class App1Config(AppConfig):
  name = 'apps.app1'

app2下的apps文件

from django.apps import AppConfig
class App2Config(AppConfig):
  name = 'apps.app2'

app1下的urls.py文件

from django.urls import path
from . import views

app_name = 'app1'

urlpatterns = [
  path('index', views.index),
]

app2下的urls.py文件

from django.urls import path
from . import views
app_name = 'app2'
urlpatterns = [
  path('index', views.index),
]

app1下的views.py文件

from django.shortcuts import render
from django.shortcuts import HttpResponse
def index(request):
  return HttpResponse('hello app1')

app2下的views.py文件

from django.shortcuts import render
from django.shortcuts import HttpResponse
def index(request):
  return HttpResponse('hello app2')

settings.py文件下的app配置:

'apps.app1.apps.App1Config', 'apps.app2.apps.App2Config'

启动

python manage.py runserver 8080

最后访问url路径

在这种设置下,在一个app访问另一个app的model

from apps.app名.models import 模型类

加载全部内容

相关教程
猜你喜欢
用户评论