【发布时间】:2020-03-27 05:41:50
【问题描述】:
这是我的看法。我使用基于函数的视图来显示帖子的详细信息。
def post_detail(request,slug,pk):
detail = get_object_or_404(Post,slug=slug,pk=pk)
context={
'detail':detail
}
return render(request,'post/post_detail.html',context)
这是我的网址。的 post_detail ,它的名字也是 post_detail
path('<int:pk>/<str:slug>/', views.post_detail, name='post_detail'),
这是我的模型。这是一个帖子模型,我有 get_absolute_url () 来渲染到详细视图
class Post(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True)
story= models.TextField()
image= models.ImageField()
slug = models.SlugField()
def get_absolute_url(self):
return reverse('post_detail',kwargs={'pk':self.pk,'slug':self.slug})
def __str__(self):
return self.title
这是我的 post_detail 视图的 post/post_detail.html
{% extends "post/base.html" %}
{% block content %}
{% for posts in detail %}
{{posts.image.url}}
{{posts.title}}
Written by: {{posts.author}}
{% endfor %}
{% endblock content %}
【问题讨论】:
标签: python django templates model