Django - 你如何在html中的for循环中获得相应的模型对象?

时间:2018-02-02 20:00:13

标签: python html django django-models

我正在尝试创建一个简单的django网站,任何用户都可以评价和创建帖子。如此django教程(https://docs.djangoproject.com/en/1.7/topics/templates/)中所示,您可以使用for循环在html中显示所有模型对象。在我的情况下,每个对象将显示一个Like和Dislike按钮,因此人们可以评价帖子。我的问题是:我如何知道哪个对象属于哪个喜欢/不喜欢按钮,以便可以为该特定对象更改相应的模型字段?谢谢你的答案!

models.py

from django.db import models

# Create your models here.

class Post(models.Model):
    post_text = models.CharField(max_length=500)
    pub_date = models.DateTimeField("date published")
    likes = models.IntegerField(default=0)
    dislikes = models.IntegerField(default=0)
    def __str__(self):
        return self.post_text

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AllPosts</title>
</head>
<body>
{% if post_list %}
<ul>
    {% for post in post_list %}
    <li>{{post.post_text}}</li>
    <p>This post has {{post.likes}} likes and {{post.dislikes}} dislikes.</p>
    <br>Leave a <button type="button" method="LIKE">Like</button> or a <button type="button" method="DISLIKE">Dislike</button>!</p>
    {% endfor %}

</ul>
<h2>If you want to create a post yourself, <a href="{% url 'create' %}">click here.</a></h2>
{% else %}
<h1>There are no posts yet...</h1>
{% endif %}


</body>
</html>

views.py

from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from django.utils import timezone
from .models import Post


# Create your views here.

def index(request):

    post_list = Post.objects.order_by('-pub_date')
    template = loader.get_template('post/index.html')
    context = {'post_list': post_list, }
    #if request.method == "LIKE":
    #    post = Post.objects.get(id=) How do I find out the id?
     #   return HttpResponse(template.render(context, request))
    #else:
    return HttpResponse(template.render(context, request))


def create(request):
    template = 'post/create.html'
    if request.method == 'POST':
        post = Post()
        post.post_text = request.POST.get("post_text")
        post.pub_date = timezone.now()
        post.save()

        return render(request, template)

    else:

        return render(request, template)

1 个答案:

答案 0 :(得分:1)

为了使按钮起作用,它们需要位于表单元素内并且为type="submit",否则单击时它们将不会执行任何操作。要确定点击了哪个按钮,您可以将method属性替换为name="like"name="dislike"。然后,可以通过将其值设置为帖子ID来将相关帖子引用到相关帖子。

以下是应该执行此操作的代码示例。我已经删除了代码中一些不相关的部分。 (注意:我没有对此进行测试,因此可能无法正常工作

index.html UL元素:

<ul>
    {% for post in post_list %}
    <li>
        <span>{{post.post_text}}</span><br>
        <p>This post has {{post.likes}} likes and {{post.dislikes}} dislikes.</p>
        <form method="post">
            <p>
                Leave a <button type="submit" name="like" value="{{post.id}}">Like</button>
                or a <button type="submit" name="dislike" value="{{post.id}}">Dislike</button>!
            </p>
        </form>
    </li>
    {% endfor %}
</ul>

views.py索引:

def index(request):
    if request.method == 'POST':
        like = request.POST.get('like')
        dislike = request.POST.get('dislike')
        if like:
            # Handle liked post
            # `like` is equal to the post ID
        else if dislike:
            # Handle disliked post
            # `dislike` is equal to the post ID
        else:
            # No action requested
    else:
        post_list = Post.objects.order_by('-pub_date')
        template = loader.get_template('post/index.html')
        context = {'post_list': post_list, }
        return HttpResponse(template.render(context, request))

我希望这会有所帮助:)