简体   繁体   English

在Django模板中显示查询集对象

[英]Display query set object in django template

I have a model Post that I'm trying to display all the posts onto a template. 我有一个模型Post ,我试图将所有帖子显示到模板上。 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 我将post.html包含到home.html中。...我发现了与我的问题类似的问题,但对象仍未得到显示链接

I firt tried the to use python manage.py shell to create an object. 我尝试使用python manage.py shell创建对象。 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. Post.objects.create(user="test", content="New comment")但收到此错误: 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. 因此,我决定将代码编写在posts / views.py中,但效果也不佳。 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 这是我的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 这是我的模板/ 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. 通常,在请求中, django自动添加请求的用户。 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: 假设用户信息存储在request.user中,则可以执行以下操作:

views.py: 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: 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". 您需要获取一个用户对象以传递给您的创建方法,而不是使用字符串“ test”。 The reason your attempt is failing is because you are passing the function a string ("test") where it is expecting a user object. 尝试失败的原因是因为您正在向函数传递期望用户对象的字符串(“ test”)。

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: 此行导入datetime模块,您需要使用该模块为create方法生成date和datetime对象:

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. 假设有两个模型A和B。B具有以下字段-x,y,z。 Now, x field is a foreign key, which is referring model A. 现在,x字段是一个外键,它引用模型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 - 现在,无论何时要创建B的对象,x字段的值都应该是A的对象。

post1 = Post(user = an object of User Model, content = "your value") post1 =发布(用户=用户模型的对象,内容=“您的值”)

so create an object of User first. 因此,首先创建一个User对象。 Then write it there. 然后在那写。 otherwise it will give error. 否则会报错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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