You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

为何我的Django URL重定向至错误地址?多App命名空间场景

Fixing Named URL Namespace Setup for Your Django Project

Got it, let's make sure your namespace configuration is spot-on so that the Startup link in your main app's base template works without a hitch. Here's the step-by-step breakdown:

1. Add the Namespace to Your Startup App's URLs

First, head over to startup/urls.py and set the app_name variable—this is what defines the namespace for all URLs in the startup app. Then make sure your index view has the correct name:

from django.urls import path
from . import views

# This line is critical for the namespace to work
app_name = 'startup'

urlpatterns = [
    # Maps the root of the startup app to your index view, named 'index'
    path('', views.index, name='index'),
]

2. Update Your Project's Main URLs File

In your project's root urls.py, ensure you're including the startup app's URLs correctly. Since we set app_name in the app's urls.py, Django will automatically recognize the startup namespace when you include it:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^main/', include('main.urls')),
    # Include the startup app's URLs—namespace is pulled from app_name
    url(r'^startup/', include('startup.urls')),
    url(r'^visit/', include('visit.urls')),
]

Your existing link in main/templates/main/base.html is already using the right syntax for namespaced URLs—great job on that! Just double-check for typos (namespace and URL names are case-sensitive):

<li class="nav-item">
    <a class="nav-link" href="{% url 'startup:index' %}">Startup</a>
</li>

Quick Troubleshooting If You Hit Issues

If you see a NoReverseMatch error, run through these checks:

  • Did you add app_name = 'startup' to startup/urls.py? This is the most common missed step.
  • Does the index URL pattern in startup/urls.py have name='index' exactly?
  • Is your main urls.py including startup.urls without typos?
  • Are there any typos in the {% url %} tag (e.g., StartUp instead of startup)?

内容的提问来源于stack exchange,提问作者Arjun Kashyap

火山引擎 最新活动