很抱歉,如果这是基本的,但我是新手。
我正在尝试创建一个包含两个参数的链接,第二个参数似乎正在工作,但第一个返回此错误:
Reverse for 'post_detail' with arguments '(<Story: Story 1>, '')' not found. 1 pattern(s) tried: ['story\\/(?P<work>[0-9]+)\\/post\\/(?P<pk>[0-9]+)\\/$']
from django.urls import path
from . import views
urlpatterns = [
path('', views.StoryListView.as_view(), name='home'),
path('story/<int:pk>/', views.PostListView.as_view(), name='story_overview'),
path('story/<int:work>/post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
]
这是模板。这会显示故事中的所有帖子,该链接会将您带到另一个显示单个帖子的页面。 work
参数是Story表中的sotry的id(它也出现在Post表中)
{% extends 'base.html' %}
{% block content %}
{% for posts in object_list %}
<h2><a href="{% url 'post_detail' work post.pk %}">{{ posts.title }}</a></h2>
<p>{{ posts.body }}</p>
{% endfor %}
{% endblock content %}
以下是我的观点:
from django.shortcuts import get_object_or_404
from django.views.generic import ListView, DetailView
from . models import Post, Story
class StoryListView(ListView):
model = Story
template_name = 'home.html'
class PostListView(ListView):
template_name = 'story_overview.html'
def get_queryset(self):
self.work=get_object_or_404(Story, pk=self.kwargs['pk'])
return Post.objects.filter(work_id=self.work)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['work'] = self.work
return context
class PostDetailView(ListView):
model = Post
template_name = 'post_detail.html'
我有这个:
path('story/<int:storyid>/post/<int:postid>/', views.PostDetailView.as_view(), name='post_detail'),
<h2><a href="{% url 'post_detail' storyid=work postid=post.pk %}">{{ posts.title }}</a></h2>
但是我收到了这个错误:
Reverse for 'post_detail' with keyword arguments '{'storyid': <Story: Story 1>, 'postid': ''}' not found. 1 pattern(s) tried: ['story\\/(?P<storyid>[0-9]+)\\/post\\/(?P<postid>[0-9]+)\\/$']
我认为问题出在我的模板和网址之间,但我无法弄清楚我做错了什么。