Django没有反向匹配,上下文破坏我的代码



我已经把它缩小到当我添加上下文到我的返回渲染(请求)行是当我的代码中断,但我不知道为什么。我不知道应该给出什么错误,也不知道你需要我代码的哪一部分,但是给你。

NoReverseMatch at /gallery/gallery
Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo']
Request Method: GET
Request URL:    http://127.0.0.1:8000/gallery/gallery
Django Version: 3.2.3
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo']
Exception Location: C:UsersScrillaGorillaPycharmProjectsMustache Websitevenvlibsite-packagesdjangourlsresolvers.py, line 694, in _reverse_with_prefix
Python Executable:  C:UsersScrillaGorillaPycharmProjectsMustache WebsitevenvScriptspython.exe
Python Version: 3.8.6
Python Path:    
['C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\mustache',
'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\python38.zip',
'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\DLLs',
'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\lib',
'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38',
'C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv',
'C:\Users\ScrillaGorilla\PycharmProjects\Mustache '
'Website\venv\lib\site-packages']
Server time:    Thu, 16 Sep 2021 06:49:31 +0000

这是我的代码。如果有帮助的话。这是我的views.py文件

from django.shortcuts import render
from .models import Category, Photo
from django.db import models

# Create your views here.
def photogallery(request):
categories = Category.objects.all()
photos = Photo.objects.all()
context = {'categories': categories, 'photos': photos}
return render(request, 'picturegallery/pictures.html', context)
def viewPhoto(request, pk):
photo = Photo.objects.get(id=pk)
return render(request,'picturegallery/photo.html', {'photo': photo})
def addPhoto(request):
return render(request,'picturegallery/ADD.html')

这是我的models.py文件

from django.db import models

# Create your models here.

class Category(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class Photo(models.Model):
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
description = models.CharField(max_length=500, null=False, blank=False)
def __str__(self):
return self.description

这是URL.py文件

from django.urls import path, include
from . import views
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url('gallery', views.photogallery, name="gallery"),
url('photo', views.viewPhoto, name="photo"),
url('add/', views.addPhoto, name="add"),
]

在我的URL.py文件中。我把代码修改成这样,它工作了。

urlpatterns = [
path('gallery', views.photogallery, name="gallery"),
path('photo/<str:pk>/', views.viewPhoto, name="photo"),
path('add/', views.addPhoto, name="add"),
]

最新更新