【发布时间】:2021-10-25 20:02:18
【问题描述】:
我想获取一个具有唯一模型字段的博客,但是当我点击一个特定的博客时,它会抛出我上面提到的错误 这是我的看法
class Blogs(View):
def get(self, request):
blog_list = Blog.objects.order_by('-joined_date')
return render(request, 'blogs.html',{'blog_list':blog_list})
class ReadBlogs(View):
def get(self, request, title):
readblog = Blog.objects.filter(title=title)
return render(request,'blogs_read.html', {'readblog':readblog})
我的模特
class Blog(models.Model):
title = models.CharField(max_length=48, blank=False)
urltitle = models.SlugField(max_length=48, blank=False, unique=True)
title_image = models.ImageField(upload_to='blog',blank=True, null=True)
subone = models.CharField(max_length=80, blank=False)
subone_image = models.ImageField(upload_to='blog',blank=True,null=True)
onedes = models.TextField(blank=False)
我的 html 用于获取正确的博客
<div class="blogs">
{% for blogs in blog_list %}
<a class="products" href="{% url 'blogs:readblog' title=blogs.urltitle %}">
<div class="blog col-4" style="width: 18rem; height:350px">
<img class="img" src="{{ blogs.title_image.url }}" alt="" height="250px" width="100%">
<div class="detail">
<h4 class="title text-center" style="color: #025; font-family:cursive;">{{blogs.title}}</h4>
</div>
</div>
</a>
{% endfor %}
</div>
我的 url.py
urlpatterns = [
path('blogs/',Blogs.as_view(),name="Blogs"),
path('<slug:title>/',ReadBlogs.as_view(),name="readblog")
]
你可以看到 mu urltitle 是唯一的 slug 字段,所以但是当我点击一个特定的博客时,我得到了上面提到的错误,不知道是什么导致了错误
我用于显示该博客相关字段的模板
<div class="col-11 card">
<div class="blogs">
{% for blog in readblog %}
<h1 class="text-center" style="color: #025; font-family:cursive; margin-top:20px;">{{read.title}}</h1>
{% endfor %}
</div>
</div>
【问题讨论】:
标签: django django-models django-views django-urls django-class-based-views