Logic is not rendered correctly

In a twitter like application, there is a functionality to show ‘posts’ of selected ‘author/post creater’. However, the html page render such at all posts of all ‘authors/post creaters’ are displayed. Filter logic is not rendered correctly. please, help.

def postCreater(request,post_creater):
    posts = Post.objects.filter(creater__username = post_creater)
    posts = posts.order_by("-dt").all()
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, "network/index_copy.html", {'page_obj': page_obj})
```
html page
```
{% for post in page_obj %}
        
    <div class="container" id="container{{post.id}}" style="border: solid;">
        <input type="button" value="{{post.creater}}" class="postCreater" id="creater{{post.id}}" onclick="viewProfile('{{post.creater}}')">
        <div class="postid" id="{{post.id}}">{{post.id}}</div>
        <textarea disabled class="pcontent" id="txtarea{{post.id}}">{{post.pcontent}}</textarea> <br>
        {% if post.creater == user %}
            <input type="button" value="Edit" class="editPost" id="edit{{post.id}}" onclick="editPost('{{post.id}}')">
            <input type="submit" value="Save" class="editPost" id="save{{post.id}}" hidden>
        {% endif %}
        <div>{{post.dt}}</div>
        <div style="cursor: pointer; height: fit-content; width: fit-content;" id="Unlike{{post.id}}" onclick="like('{{post.id}}')">&#129293;</div>
        <div style="cursor: pointer; height: fit-content; width: fit-content;" id="like{{post.id}}" onclick="like('{{post.id}}')" hidden>&#65039;</div>
      </div>
    {% endfor %}
```
Java script
```
function viewProfile(postCreater){

  event.preventDefault();
  document.getElementById("AllPost").style.display = 'none';
  document.getElementById('newPost').style.display = 'none';
  document.getElementById('userProfile').style.display = 'none';
 
  if (postCreater != document.getElementById('Profile').innerText){
    document.getElementById("postCreaterProfile").style.display = 'block';
    document.getElementById('userName').style.display = 'none';
    document.getElementById('PostCreaterName').style.display = 'block';
    document.getElementById('PostCreaterName').innerText = postCreater;
    post_creater = postCreater

    fetch('/posts/' + post_creater)
    .then(response => response.status)
    .then(posts => {
      console.log(posts);
       
  })
  }
  else{
    document.getElementById("postCreaterProfile").style.display = 'none';
    document.getElementById('PostCreaterName').style.display = 'none';
    post_creater = postCreater

    fetch('/posts/' + post_creater)
    .then(response => response.status)
    .then(posts => {
      console.log(posts);
       
  })

}
}
```

Don’t try to do it in your template, do the filtering in your view.

You’ve got:

posts = Post.objects.filter(creater__username = post_creater)
posts = posts.order_by("-dt").all()

You don’t need (or want) the .all() on the second statement. In fact, you can simplify it as:

posts = Post.objects.filter(creater__username=post_creater).order_by('-dt')

Thanks for the suggestion. However, filtering is not working in html.
I mean eventhough ‘view’ filter posts as per the creater, html does not show filtered post.

Sorry, I don’t understand what you’re saying here. Can you be more specific and provide more detail about what the issue is?

I have single page application. Without ‘filter’ all posts are displayed.
However, with ‘filter’, all posts are displayed which is not expected.
Somehow html is not picking the rendering from ‘view’ function.

Did you remove the .all() function as I mentioned at first?

yes. i did. I removed it.

And you can verify that this query:
posts = Post.objects.filter(creater__username = post_creater).order_by("-dt")
returns only the posts you want to see? (Tested within the shell)

Might be useful if you posted your urls.py file that assigns the URLs to your postCreater view.

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),

    # API Routes
    path("posts", views.index, name="index"),
    path("posts/all", views.posts, name="posts"),
    path("posts/<int:post_id>", views.postEdit, name="postEdit"),
    path("posts/<str:post_creater>", views.postCreater, name="postCreater"),
   ]

I have tried JsonResponse just to see the output in ‘console.log’ and it does show correct output. However, somehow hmtl rendering is not working.

However, somehow hmtl rendering is not working.

Again, simply saying something is not working doesn’t provide us with any information making it possible to try and provide assistance.

You wrote:

I have tried JsonResponse just to see the output in ‘console.log’ and it does show correct output.

So what “is not working”?

What have you done to try and identify or narrow down the scope of the issue?

You’re using a paginator, but none of the template posted renders any of the paginator components - is that at all part of this? If not, have you tried removing it?

What is the actual HTML being rendered? Have you tried rendering it to a string and printing that string to see what’s being rendered? Or have you checked the developer tools to look at the response being sent by the server?

Thanks for the inputs. HTML is showing all posts without ‘filter’.
‘view’ function is rendering HTML with ‘filtered’ posts. However, in HTML ,‘Filter’ logic is not working.

I tried to change HTML rendering to JsonResponse to see the output in ‘console’ in developer tools. Console did show that posts gets ‘filtered’ in JsonResponse.

There is no “filter logic” in the HTML. A template does not do any filtering, a template is used in the render process to produce HTML from data supplied to it in the context.

Please identify the specific line(s) that you’re referring to where you think some “filter logic” exists.

{% for post in page_obj %}

Above line in HTML showing all posts. That means, ‘page_obj’ somehow is not got filtered in ‘View’ function.

You’re looking at this the wrong way.

The template does not filter the data. The template renders data being supplied to it. If the view is producing the right data, that’s all that the template can render.

If the template is rendering something other than what you think the view is supplying, then either -

  • The view is doing something you’re not expecting,

or

  • You’ve got a different view using the same template, and it’s that other view being called.

I agree. The ‘view’ logic is the main reason for this. But, I am not sure how to correct it.
There is another view as below,

def posts(request):
    posts = Post.objects.all()

    # Return posts in reverse chronologial order
    posts = posts.order_by("-dt").all()
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'index.html', {'page_obj': page_obj})

I suspect it is getting called.
Is there any way to ‘prevent’ it from calling?

So you’ve got at least two urls possibly involved:

path("posts/all", views.posts, name="posts"),

and

path("posts/<str:post_creater>", views.postCreater, name="postCreater"),

Check your console log where you’re running this (either runserver or runserver_plus if this is a development environment, or your gunicorn / uwsgi logs if it’s a production environment) to see what URLs are being requested by the browser.

Also, what’s the views.index view? Does it also use that same template? That seems to me that it would be a more likely candidate due to not having any URL component after “posts/”.

all ‘view’ are using the same HTML template.

So verify what URL is being requested by the browser. It’s beginning to sound like your browser isn’t requesting the right URL.

[29/Jul/2021 03:31:34] "GET /posts/bill HTTP/1.1" 200 5555
[29/Jul/2021 04:07:31] "GET /posts/kim HTTP/1.1" 200 5182
[29/Jul/2021 04:07:39] "GET /posts/bill HTTP/1.1" 200 5555
[29/Jul/2021 04:07:48] "GET /posts HTTP/1.1" 200 6866

It seems the urls are requesting correctly. For example, filtering as per username.