简体   繁体   中英

Django home page URL being rendered as a different URL

So, I have a simple home page for a django project I am working on. In the upper left hand corner is the logo for the site. In my template, I have this code:

<a href="{% url "home" %}">Company Name</a>

In my root urls.py, I have this:

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
   url(r'^$', include('app.urls')),          # The main app
   url(r'^login/$', include('app.urls')),     # The login page
)

and in my app/urls.py I have this:

from django.conf.urls import patterns, url
from app import views

urlpatterns = patterns('',
      url(r'^$', views.index, name='home'),             # The homepage of the website
      url(r'^login/$', views.loginView, name='login'),  # The login page of the website
)

Now you would think (or at least I would) that when the index page is rendered, it would generate the html <a href="/">Company Name</a> or something similar. Instead, what I get is <a href="/login/">Company Name</a> .

So, why happen? Obviously, this is unwanted behavior. I am almost certain the issue is in the url configuration, but I could be wrong.

Please and thankyou

You are including the same URLpatterns twice. Your main urls.py should just be:

urlpatterns = patterns('',
   url(r'', include('app.urls')),
)

Then your URLs will resolve/reverse as expected.

This happens because you are including the same file app.urls under two relative paths , namely / and /login . So, the right url name definition is just overwritten.

To avoid this, do not include the same url config file under two relative paths. So, in your case, you should create a new url config file (say login.urls ), move login related url definitions to that new file and replace the root url config with

from django.conf.urls import patterns, url
from app import views

urlpatterns = patterns('',
    url(r'^$', include('app.urls')),          # The main app
    url(r'^login/$', include('login.urls')),     # The login page
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM