简体   繁体   中英

ValueError - Invalid literal for int() with base 10: 'add' caused by Django URLs

Here is my urls.py code,

from django.contrib import admin
from django.urls import path
from . import views

app_name = 'stories'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<pk>', views.DetailView.as_view(), name='detail'),
  #  path('<story_id>/ratings', views.rating, name='rating'),
    path('add', views.CreateStory.as_view(), name='add-story'),
] 

I get above error when click the link,

 <li><a href="{% url 'stories:add-story' %}">Click me</a></li>

And my views.py file includes following,

from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Story

class CreateStory(CreateView):
    model = Story
    fields = [' story_title', 'story_content', 'story_rating']

Your URL /add/ is being handled by the detail view, and gives a ValueError because add is not an integer primary key.

There are two things you can change, either should fix the problem.

Firstly, move the add-story URL pattern above detail so that /add/ is matched by the add-story URL pattern first.

Secondly, change the group to <int:pk> to tell Django that pk should be an integer, so that it doesn't match strings like 'add' .

path('add', views.CreateStory.as_view(), name='add-story'),
path('<int:pk>', views.DetailView.as_view(), name='detail'),

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