[英]UnboundLocalError: local variable 'r' referenced before assignment (Django)
[英]Django UnboundLocalError: local variable 'tags' referenced before assignment
為什么我會遇到這個問題? 我正在嘗試從 Post 表中獲取標簽。Post 和標簽是兩個具有多對多關系的表。
在模型.py
class Tag(models.Model):
caption = models.CharField(max_length=40)
class Post(models.Model):
tags = models.ManyToManyField(Tag)
在視圖中
def post_details(request,slug):
post = Post.objects.get(slug=slug)
tags = Post.objects.filter(tags)
comment = post.comments.all()
return render (request,'mblog/post_detail.html',{'post': post ,'tags': tags,'comment': comment})
你可能想更換
tags = Post.objects.filter(tags)
簡單地
tags = post.tags
tags = Post.objects.filter(
沒有意義:您正在過濾tags )Post
對象,而不是Tag
對象,並且您正在使用一個名為tags
的變量,甚至在分配該變量之前。 您可能想使用post .tags.all()
:
from django.shortcuts import get_object_or_404
def post_details(request, slug):
post = get_object_or_404(Post, slug=slug)
tags = post.tags.all()
comment = post.comments.all()
return render(
request,
'mblog/post_detail.html',
{'post': post, 'tags': tags, 'comment': comment},
)
注意:通常最好使用
get_object_or_404(…)
[Django-doc] ,然后直接使用.get(…)
[Django-doc] 。 In case the object does not exists, for example because the user altered the URL themselves, theget_object_or_404(…)
will result in returning a HTTP 404 Not Found response, whereas using.get(…)
will result in a HTTP 500 Server Error .
您需要在訪問 tags 變量之前對其進行初始化。
試試這個代碼:
tags = Tag.objects.all()
posts = tags.Post.all()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.