Slug 没有在 Django 2.0 中呈现详细信息页面
Posted
技术标签:
【中文标题】Slug 没有在 Django 2.0 中呈现详细信息页面【英文标题】:Slug not rendering detail page in Django 2.0 【发布时间】:2019-08-14 13:03:04 【问题描述】:在这种情况下使用 slug 并使其正常工作的最佳方法是什么。我可以在浏览器上看到 URL 显示请求的项目,但我无法呈现详细页面。我找不到问题出在哪里。当我访问“page_detail”时,url 是“http://127.0.0.1:8000/posts/2019/03/23/greetings/”,根据我的输入这是正确的,但是 django 会抛出错误来呈现页面。错误是:TypeError: post_detail() got an unexpected keyword argument 'slug'
型号:
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
published = PublishedManager() # Custom Model Manager
def get_absolute_url(self):
''' Canonical URL for post detail.'''
return reverse('snippets:post-detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
网址
app_name = 'snippets'
urlpatterns = [
path('posts/', views.post_list, name='post-list'),
path('posts/<int:year>/<int:month>/<int:day>/<slug:slug>/', views.post_detail, name='post-detail'),
]
观看次数
def post_list(request):
posts = Post.published.all()
context = 'posts': posts
return render(request, 'snippets/list.html', context)
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'snippets/detail.html', 'post':post)
post_list HTML
% extends "base.html" %
% block title %My Blog% endblock %
% block content %
<h1>Blog</h1>
% for post in posts %
<h2>
<a href=" post.get_absolute_url ">
post.title
</a>
</h2>
<p class="date">
Published post.publish by post.author
</p>
post.body|truncatewords:30|linebreaks
% endfor %
% endblock %
post_detail HTML
% extends "base.html" %
% block title % post.title % endblock %
% block content %
<h1> post.title </h1>
<p class="date">
Published post.publish by post.author
</p>
post.body|linebreaks
% endblock %
我还是卡住了。任何帮助将不胜感激。
【问题讨论】:
【参考方案1】:尝试将您的views.py更改为
def post_detail(request, year, month, day, slug):
post = get_object_or_404(Post, slug=slug,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'snippets/detail.html', 'post':post)
【讨论】:
以上是关于Slug 没有在 Django 2.0 中呈现详细信息页面的主要内容,如果未能解决你的问题,请参考以下文章
Django 2.0 slug urls.py 意外关键字参数“slug”