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

问题描述 投票:0回答:1

我有一个指向我的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>

但是,如果单击“添加相册”链接,则会导致错误:

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

music / 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"),
]

任何人都可以发现错误来解决问题吗?我需要“添加相册”链接转到album_form.html页面。 music / templates / music / album_form.html(包含album_form,包括表单模板。

django views render
1个回答
1
投票

您的“详细”网址模式过于笼统,正在捕捉所有内容 - 包括字符串'album-add'。你应该做两件事:用"<int:pk>/"将它约束为一个整数,和/或在专辑添加模式之后移动它。

© www.soinside.com 2019 - 2024. All rights reserved.