【问题标题】:Django url with multiple slugs, no reverse match error带有多个 slug 的 Django url,没有反向匹配错误
【发布时间】: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


【解决方案1】:

您的错误发生在/,由getCatTypePosts 处理。此视图不会将 categoryTypeSlugpostTitleSlug 添加到上下文中,因此您的 {% url %} 标记会给出错误,指出关键字参数是 ''

由于{% url %} 标记位于{% for post in posts %} for 循环内,您可以使用post.postTitleSlug 代替postTitleSlug。如何替换 categoryType 不太明显,因为它是多对多字段 - 不清楚您想在那里使用什么值。您可以使用post.categoryType.first.categoryTypeSlug,只要每个帖子至少有一个相关类别。

【讨论】:

  • 谢谢@Alasdair,请问您说使用时,您指的是哪里?
  • 在给出错误的 url 标签{% url 'getPost' categoryTypeSlug postTitleSlug %} 中。
  • 对不起,我在这里真的很笨。您是否建议将模板更改为
    {% url 'getPost' categoryTypeSlug=post.categoryType.first.categoryTypeSlug postTitleSlug %}
  • 正如我所说,您需要将 both categoryTypeSlugpostTitleSlug 替换为某些内容。您无需添加categoryTypeSlug=
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2017-04-25
  • 2013-01-04
  • 2011-11-03
相关资源
最近更新 更多