简体   繁体   中英

Display query set object in django template

I have a model Post that I'm trying to display all the posts onto a template. I'm including the post.html onto the home.html.... I found a similar problem to my question but the objects still are not getting displayed link

I firt tried the to use python manage.py shell to create an object. So first I did this. Post.objects.all() <QuerySet [<Post: test>, <Post: admin>]>

then I tried to create a new posts. Post.objects.create(user="test", content="New comment") but got this error: ValueError: Cannot assign "'test'": "Post.user" must be a "User" instance.

Tried to troubleshoot and couldn't resolve it. So I just decided to write the code in the posts/views.py and it didn't work as well. I figure this is the root of my problem why the objects aren't showing up in the templates.

This is my posts/posts.views


def posts_list(request):
    # if request.user.is_authenticated():
    queryset = Post.objects.all()
    context = {
        "object_list": queryset,
        "user": "username"
    }
    return render(request, "posts.html", context)

This is my templates/post.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1>What's on your mind, {{ user }}</h1>
    { % for obj in object_list %}
    {{obj.user}}<br/>
    {{obj.content}}<br/>
    {{obj.timestamp}}<br/>
    {% endfor %}

  </body>
</html>

Normally in request, django automatically add requested user. If that user has related permission to add new Post then following code should work

Post.objects.create(user=request.user, content="New comment")

You have asked two questions here. I'll answer both of them below:

Displaying your posts

First, you need to make sure that you are passing a user object to your template. Assuming that user info is stored in request.user, you can do so as follows:

views.py:

def posts_list(request):

    if request.user.is_authenticated:

        user = request.user
        queryset = Post.objects.all()

        context = {
            "object_list": queryset,
            "user": user
        }

        return render(request, "home.html", context)

home.html:

<html>
<h1>Homepage</h1>
{% if user.is_authenticated %}
<h1>What's on your mind, {{ user }}</h1>
    { % for obj in object_list %}
    {{obj.user}}<br/>
    {{obj.content}}<br/>
    {{obj.timestamp}}<br/>
    {% endfor %}
<a href="{% url 'logout' %}">Logout</a>
{% endif %}
</html>

Adding a post for a user

You need to get a user object to pass to your creation method, rather than using the string "test". The reason your attempt is failing is because you are passing the function a string ("test") where it is expecting a user object.

This line gets a user (arbitrarily grabs the first one in your list):

u = User.objects.all()[0]

This line imports the datetime module, which you'll need to generate date and datetime objects for your create method:

import datetime

And this line creates a post for that user:

Post.objects.create(user=u, content="New comment", publish=datetime.date.today(), updated=datetime.datetime.now(), timestamp=datetime.datetime.now())

When you are creating a foreign key, you are referring a model. suppose there are two models A and B. B has following fields - x, y, z. Now, x field is a foreign key, which is referring model A.

Now whenever you want to create an object of B, then the value of x field should be an object of A. Little bit like this -

post1 = Post(user = an object of User Model, content = "your value")

so create an object of User first. Then write it there. otherwise it will give error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM