Django项目:base.html中的链接导致错误

时间:2017-12-28 13:22:34

标签: django views render

我有一个链接到"添加相册"在我的Django项目的base.html中指定。 代码低于

 <ul class="nav navbar-nav navbar-right">
                <li class="">
                    <a href="{% url 'music:album-add' %}">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Album
                    </a>
                </li>

当&#34;添加相册&#34;但是,点击链接会导致错误:

ValueError at /music/album-add/
invalid literal for int() with base 10: 'album-add'
Request Method: GET
Request URL:    http://127.0.0.1:8000/music/album-add/
Django Version: 2.0
Exception Type: ValueError
Exception Value:    
invalid literal for int() with base 10: 'album-add'
Exception Location: C:\Python34\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 947

音乐/ views.py文件代码位于

之下
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Album

#=============HOME PAGE===================
class IndexView(generic.ListView):
    #specify template being used
    template_name='music/index.html' #when we get a list of all albums, plug them into this template
    context_object_name='all_albums' #if you don't use this variable it is automatically just object_list (which is used in index.html)

    #make a query set
    def get_queryset(self):
        return Album.objects.all()


#=============DETAILS VIEW=============== details about one object
class DetailView(generic.DetailView):
    #what model are we looking at /for
    model=Album
    template_name='music/detail.html'

#===============For the add album form  
class AlbumCreate(CreateView):
    model=Album
    fields=['artist','album_title','genre','album_logo']
    template_name='music/album_form.html'

urls.py代码:

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

from . import views #the dot means look at the current directory - look for a module called views

app_name='music'

urlpatterns = [
    #this is matching /music/
     path('', views.IndexView.as_view(), name='index'),
     #when you use a detail view it expects a primary key
     path("<pk>/", views.DetailView.as_view(), name="detail"),
     #/music/album/add - dont need to specify pk
     path('album/add/', views.AlbumCreate.as_view(), name="album-add"),
]

有人能发现错误来解决问题吗?我需要&#34;添加专辑&#34;链接转到album_form.html页面。 music / templates / music / album_form.html(包含album_form,包括表单模板。

1 个答案:

答案 0 :(得分:1)

你的&#34;细节&#34;网址格式太笼统,并且正在捕捉所有内容 - 包括字符串&#39; album-add&#39;。您应该做两件事:将其约束为"<int:pk>/"的整数,和/或在相册添加模式之后移动它。