当我访问 http://localhost:8000/details/A1/ 时,我收到此错误“字段 'id' 需要一个数字,但得到了 'A1'”。
我做错了什么?
models.py
class Chips(models.Model):
id = models.AutoField(primary_key=True)
brand = models.CharField(max_length=300)
cost = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return "{}: {}, {}".format(
str(self.pk),
self.brand,
self.cost,
)
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import *
def details(request, pk):
w = get_object_or_404(Chips, pk=pk)
return render(request, 'MyApp/details.html', {'w': w})
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('details/<pk>/', views.details, name='details'),
]
答案 0 :(得分:0)
您的 id
是 AutoField
,因此它存储整数,因此 A1
不能是 Chips
对象的有效主键.
因此,您首先应该看看为什么会得到 A1
,因为它没有任何意义。您可能还最好为 <pk>
提供 <int:…>
路径转换器,以防止视图被非整数路径触发:
urlpatterns = [
path('details/<int:pk>/', views.details, name='details'),
]