【发布时间】:2018-03-25 08:57:07
【问题描述】:
我在 Django 中有一个博客项目,我希望能够根据帖子类型过滤我的帖子,例如旅游帖子、编程帖子。因此,在我的模板中,我需要通过帖子 slug 和类型 slug 过滤帖子,但我得到了:
NoReverseMatch 在 / 使用关键字参数 '{'categoryTypeSlug': '', 'postTitleSlug': ''}' 反向搜索 'getPost'。尝试了 1 种模式:['categories/(?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 %}
我的模型.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)
网址配置
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'),
]
非常感谢任何帮助。
【问题讨论】:
-
请注意,在 Python/Django 中,建议使用 CamelCase 作为模型名称(例如
CategoryType和 lowercase_with_underscores 作为字段名称(例如category_type_slug或简单的slug)。跨度>
标签: django django-models django-templates django-views django-urls