0

I am trying to ad a condition into an html model in Django (python) and it is not working:

This is my HTML:

                    <p class="card-text text-muted h6">{{ post.author }} </p>
                    {% if post.author  == 'John_Woo' %}
                    <p class="card-text text-muted h6"> NOK </p>
                    {% else %}
                    <p class="card-text text-muted h6"> ok </p>
                    {% endif %}

Not sure what is wrong here... Even though I have a John_Woo author, I only get ok message

This is my models.py:

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')

This is my views.py:

from django.views import generic
from .models import Post

class PostList(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'
3
  • Can you show the code to your views.py and models.py files? Commented Oct 31, 2019 at 11:34
  • Almost certainly, author is a ForeignKey, so it will never equal a string. But show your model. Commented Oct 31, 2019 at 11:36
  • Edited with views.py and models.py Commented Oct 31, 2019 at 11:37

2 Answers 2

1

Post.author returns class's representation like(str, unicode, repr) function. You have to override this functions which is depends on your django version. But you have one way to compare this. Like if Post.author.first_name == "John_Woo"

Sign up to request clarification or add additional context in comments.

Comments

1

You want post.author.name (where .name is whatever field of an User object that will sometimes contain the string 'John_Woo' )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.