完整错误:
未找到带有参数'(38,)'的'post-detail'。
尝试了1个模式:
['(?P [^ /] +)/ posts /(?P [0-9] +)/ $']
models.py
class Post(models.Model):
article_title = models.CharField(max_length=100)
content = models.TextField()
date_published = models.DateTimeField(db_index=True, default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png', upload_to='article_pics')
platform = models.CharField(default='PC', max_length=20)
def __str__(self):
return self.article_title
class Meta:
ordering = ["-date_published"]
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
twitter = models.CharField(max_length=50, default='')
def __str__(self):
return self.title
views.py
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_published')
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context
class PostDetailView(DetailView):
model = Post
urls.py
path('<str:title>/posts', TitlePostListView.as_view(), name='title-posts'),
path('<str:title>/posts/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
我正在尝试使路径类似于domain.com/Minecraft/posts/38,但出现错误,可能是因为未定义str:title。我不确定如何将其添加到我的PostDetailView中。
编辑:
post-detail.html
{% extends "main/base.html" %}
{% load static %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'main/css/post_detail.css' %}">
{% endblock styles %}
{% block content %}
<div class="container black container-position">
<div class="row">
<article class="media content-section">
<div class="media-body">
<h2 class="article-title">{{ object.article_title }}</h2>
<div class="article-content">{{ object.content|safe }}</div>
</div>
</article>
</div>
</div>
{% endblock content %}
答案 0 :(得分:0)
在此行:
return reverse('post-detail', kwargs={'pk': self.pk})
您缺少其他必需的参数title
,它应该类似于:
return reverse('post-detail', kwargs={'pk': self.pk, 'title': 'sometitle'})
看看错误中显示的模式:
['(?P [^ /] +) /帖子/(?P [0-9] +)/ $']
在第一部分中,您可以看到(?P[^/]+)
的加号(+)表示“至少一个字符”,因此标题不允许为空,并且您还没有为该情况定义URL模式,因此是错误。