我在Django有一个博客项目,我希望能够根据帖子的类型过滤我的帖子,例如旅游帖子,编程帖子。因此,在我的模板中,我需要通过post slug和类型slug来过滤帖子,但我得到了:
NoReverseMatch at / 反向' getPost'使用关键字参数' {' categoryTypeSlug':'',' postTitleSlug':''}'未找到。尝试了1种模式:['类别/(?P [\ w \ - ] +)/(?P [\ w \ - ] +)/ $']
我的简化模板(getCatTypePosts.html):
{% block content %}
{% for post in posts %}
{% if post.show_in_posts %}
<a href="{% url 'getPost' categoryTypeSlug postTitleSlug %}">
<img src="{{ MEDIA.URL }} {{post.editedimage.url}}" alt="image-{{post.title}}"/>
{% endif %}
{% endfor %}
{% endblock content %}
我的models.py
class categoryType(models.Model):
title = models.CharField(max_length=200)
categoryTypeSlug = models.SlugField(unique=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "categoryTypes"
def save(self, *args, **kwargs):
self.categoryTypeSlug = slugify(self.title)
super(categoryType, self).save(*args, **kwargs)
class Post(models.Model):
title = models.CharField(max_length=200)
postTitleSlug = models.SlugField()
summary = models.CharField(max_length=500, default=True)
body = RichTextUploadingField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
categoryType = models.ManyToManyField('categoryType')
author = models.ForeignKey(User, default=True)
authorSlug = models.SlugField()
editedimage = ProcessedImageField(upload_to="primary_images",
null=True,
processors = [Transpose()],
format="JPEG")
show_in_posts = models.BooleanField(default=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.postTitleSlug = slugify(self.title)
self.authorSlug = slugify(self.author)
super(Post, self).save(*args, **kwargs)
观看次数
def getCatTypePosts(request, categoryTypeSlug='Travel'):
posts = Post.objects.all()
posts = posts.filter(categoryType__title='Travel')
posts = posts.order_by('-pub_date')
context = {
'posts':posts,
}
return render(request, 'posts/getCatTypePosts.html', context)
def getPost(request, postTitleSlug, categoryTypeSlug):
post = Post.objects.all()
categoryTypeSlug =
post.filter(categoryType__categoryTypeSlug=categoryTypeSlug)
postTitleSlug = post.filter(post.postTitleSlug)
context = {
'post':post,
'categoryTypeSlug':categoryTypeSlug,
'postTitleSlug':postTitleSlug,
}
return render(request, 'posts/getPost.html', context)
网址conf
urlpatterns = [
url(r'^$', views.getCatTypePosts, name='home'),
url(r'^categories/(?P<categoryTypeSlug>[\w\-]+)/(?P<postTitleSlug>
[\w\-]+)/$', views.getPost, name='getPost'),
url(r'^posts/(?P<categoryTypeSlug>[\w\-]+)/$',
views.getCatTypePosts, name = 'getCatTypePosts'),
]
任何帮助非常感谢。
答案 0 :(得分:1)
您的错误发生在/
,由getCatTypePosts
处理。此视图不会向上下文添加categoryTypeSlug
和postTitleSlug
,因此您的{% url %}
代码会显示错误消息,说明关键字参数为''
。
由于{% url %}
代码位于{% for post in posts %}
for循环内,因此您可以使用post.postTitleSlug
代替postTitleSlug
。如何替换categoryType
并不太明显,因为它是一个多对多的领域 - 目前尚不清楚你想在那里使用什么价值。您可以使用post.categoryType.first.categoryTypeSlug
,只要每个帖子至少有一个相关类别。