Home > front end >  Django UnboundLocalError: local variable 'tags' referenced before assignment
Django UnboundLocalError: local variable 'tags' referenced before assignment

Time:09-12

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.

in models.py

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

CodePudding user response:

You probably want to replace

tags = Post.objects.filter(tags) 

with simply

tags = post.tags

CodePudding user response:

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(
        request,
        'mblog/post_detail.html',
        {'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.

CodePudding user response:

You need to initialize the tags variable before accessing it.

Try this code:

tags = Tag.objects.all()
posts = tags.Post.all()
  • Related