Django UnboundLocalError: local variable 'tags' referenced before assignment

Why do I face this problem? I am trying to get the tags from the Post table.Post and tags are two tables with Many to Many relation.


class Tag(models.Model):
    caption = models.CharField(max_length=40)

class Post(models.Model):
    tags = models.ManyToManyField(Tag)

in views

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})

You probably want to replace

tags = Post.objects.filter(tags) 

with simply

tags = post.tags

The tags = Post.objects.filter(tags) makes no sense: you are filtering Post objects, not Tag objects, and you are using a variable named tags before that variable is even assigned. You probably want to use 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(
        {'post': post, 'tags': tags, 'comment': comment},

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

You need to initialize the tags variable before accessing it.

Try this code:

tags = Tag.objects.all()
posts = tags.Post.all()
Back to Top