在django中使用命名空间来获取锚标记

时间:2018-01-02 11:59:10

标签: python html django url

我在django中很顽固,在3周之前开始django。我在html页面中遇到关于锚标记中url的问题。我包含所有文件

music urls.py

from django.conf.urls import url 
from . import views
app_name = 'music'
urlpatterns = [
      url(r'^$', views.index,name='music index'),
      url(r'^albums/$', views.albums,name='albums'),
      url(r'^albums/(?P<album_id>[0-9]+)/details/$',views.album,name='details')
]

main urls.py

from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
      url(r'^$', include('music.urls')),
      url(r'^music/', include('music.urls')),
      url(r'^admin/', admin.site.urls),
]

music views.py

from django.shortcuts import render , get_object_or_404
from .models import Albums,Music
def index(request):
      return render(request,'music/index.html',{})
def albums(request): 
      all_albums = Albums.objects.all()
      return render(request,'music/index.html',{'allalbums' : all_albums})
def album(request,album_id):
      single_album = get_object_or_404(Albums,pk=album_id)
      return render(request,'music/details.html' ,{'album' : single_album})

的index.html

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<ul>
		<h1>This is music Page</h1>
		{% for album in allalbums %}
			<li><a href="{% url 'music:details' album.id %}">{{ album.album_name}}</a></li>
		{% endfor %}	
	</ul>
	
</body>
</html>
&#13;
&#13;
&#13;

settings.py

INSTALLED_APPS = [
'music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

但是当我运行这段代码时,我遇到了这个问题(附加图片)..还有一件事......我正在使用linux,django 1.11.7版本 enter image description here

2 个答案:

答案 0 :(得分:1)

经过长时间的研究和实验,我找到了解决方案,我正在解决问题

music urls.py

from django.conf.urls import url 
from . import views
# app_name = 'music' <- remove from here
urlpatterns = [
  url(r'^$', views.index,name='music index'),
  url(r'^albums/$', views.albums,name='albums'),
  url(r'^albums/(?P<album_id>[0-9]+)/details/$',views.album,name='details')
]

从urls.py中删除 app_name ='music',然后在include中添加 namespace =“movies” namespace =“music”方法,在root / main urls.py

中声明urls页面之后

root urls.py

from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
  url(r'^$', include('home.urls')),
  url(r'^movies/', include('movies.urls',namespace="movies")), #added here
  url(r'^music/', include('music.urls',namespace="music")), #added here
  url(r'^admin/', admin.site.urls),
]

这样可以正常工作,我认为它仅适用于1.x版本,但在上面的2.x版本(关于问题)技术将完美运行

答案 1 :(得分:0)

更改为:

{% for album in allalbums %}
    <li><a href="/music/albums/{{album.id}}/details/">{{ album.album_name}}</a></li>
{% endfor %}