代码之家  ›  专栏  ›  技术社区  ›  Compoot

Django项目:链接到base。html导致错误

  •  0
  • Compoot  · 技术社区  · 7 年前

    我有一个指向“添加相册”的链接,该链接在基础中指定。Django项目中的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
    

    音乐/视图。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'
    

    URL。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\u表单。html页面。音乐/模板/音乐/唱片集\表单。html(包含album\u表单,包括表单模板)。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Daniel Roseman    7 年前

    您的“detail”URL模式太笼统,正在捕获所有内容,包括字符串“album add”。您应该做两件事:使用 "<int:pk>/" ,和/或将其移动到相册添加模式之后。