【问题标题】:How to build a like/dislike function Django Template如何构建一个喜欢/不喜欢的功能 Django 模板
【发布时间】:2020-12-05 09:19:06
【问题描述】:

我目前正在开发一个管理书籍的 django 页面。不同的用户可以输入和评价书籍。评分系统是我的 Django 页面上的向上/向下(喜欢/不喜欢)按钮。如果您按“向上”,则用户只能投票“向下”。如果您按“向下”,则用户只能投票“向上”。不幸的是,它没有按预期工作。如果有多个赞成或反对票,则会发生以下情况: 如果用户尚未投票“赞成”,您可以选择“赞成”。但不是“下降”。如果我随后以用户身份按“向上”,则只能再次选择“向上”。如果我更改用户,例如testuser1 到 testuser2,然后作为 testuser2 我应该有不同的选择,比如 testuser1。但这种情况并非如此。我能做什么?

{% comment %} nobody votes{% endcomment %}
{% if that_one_book.get_upvotes_count == 0 and that_one_book.get_downvotes_count == 0%}
<span style="color: darkgreen">{{ upvotes }}</span>
<a href="{% url 'book-vote' that_one_book.id 'up' %}" style="text-decoration: none">
<img src="{% static 'Books/arrow_up.png' %}" height="20" width="20">
</a>
<span style="color: crimson">{{ downvotes }}</span>
<a href="{% url 'book-vote' that_one_book.id 'down' %}" style="text-decoration: none">
<img src="{% static 'Books/arrow_down.png' %}" height="20" width="20">
</a>
{% endif%}
{% comment %}--------------------------------------------------------------------------------{% endcomment %}

{% comment %} at least one person votes {% endcomment %}
{% if that_one_book.get_upvotes_count >= 1 or that_one_book.get_downvotes_count >= 1%}
{% for post in that_one_book.get_downvotes%}
{% comment %} if user votes down{% endcomment %}
{%if request.user.username == post.myuser.username%}
{% comment %} just see the voting result{% endcomment %}
<span style="color: darkgreen">{{ upvotes }}</span>
<img src="{% static 'Books/arrow_up.png' %}" height="20" width="20">
<span style="color: crimson">{{ downvotes }}</span>
<img src="{% static 'Books/arrow_down.png' %}" height="20" width="20">
{{ "<!--" }}
{% else %}

{% comment %} only up choice.{% endcomment %}
<span style="color: darkgreen">{{ upvotes }}</span>
<a href="{% url 'book-vote' that_one_book.id 'up' %}" style="text-decoration: none">
<img src="{% static 'Books/arrow_up.png' %}" height="20" width="20">
</a>
<span style="color: crimson">{{ downvotes }}</span>
<img src="{% static 'Books/arrow_down.png' %}" height="20" width="20">
{{ "<!--" }}
{% endif %}
{% endfor %}

{% comment %}--------------------------------------------------------------------------------{% endcomment %}
{% for post2 in that_one_book.get_upvotes%}
{% comment %} if you vote up{% endcomment %}
{%if request.user.username == post2.myuser.username%}
{% comment %} just see voting result{% endcomment %}
<span style="color: darkgreen">{{ upvotes }}</span>
<img src="{% static 'Books/arrow_up.png' %}" height="20" width="20">
<span style="color: crimson">{{ downvotes }}</span>
<img src="{% static 'Books/arrow_down.png' %}" height="20" width="20">
{{ "<!--" }}

{% else %}
{% comment %} only down choice{% endcomment %}
<span style="color: darkgreen">{{ upvotes }}</span>
<img src="{% static 'Books/arrow_up.png' %}" height="20" width="20">
<span style="color: crimson">{{ downvotes }}</span>
<a href="{% url 'book-vote' that_one_book.id 'down' %}" style="text-decoration: none">
<img src="{% static 'Books/arrow_down.png' %}" height="20" width="20">
</a>
{{ "<!--" }}
{% endif %}
{% endfor %}
{% endif %}


models.py
title = models.CharField(max_length=100)
    subtitle = models.CharField(max_length=100,
                                blank=True)
    author = models.CharField(max_length=50)
    pages = models.IntegerField()  # Must call function to take effect
    date_published = models.DateField(blank=True,
                                      default=date.today,
                                      )
    type = models.CharField(max_length=1,
                            choices=BOOK_TYPES,
                            )
    myuser = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE,
                             related_name='book_created_by',
                             related_query_name='book_created_by',
                             )
    def check_date_published(self):
        print('----- In Book.check_date_published():', self.date_published, 'vs.', date.today())

        if self.date_published > date.today():
            print('----- Warning: date_published is in the future')
            return False
        else:
            return True

    def get_full_title(self):
        return_string = self.title
        if self.subtitle:  # if subtitle is not empty
            return_string = self.title + ': ' + self.subtitle
        return return_string



    def get_upvotes(self):
        upvotes = Vote.objects.filter(up_or_down='up',
                                      book=self)
        return upvotes

    def get_upvotes_count(self):
        return len(self.get_upvotes())

    def get_downvotes(self):
        downvotes = Vote.objects.filter(up_or_down='down',
                                        book=self)
        return downvotes



    def get_downvotes_count(self):
        return len(self.get_downvotes())



    def vote(self, myuser, up_or_down):
        vote = Vote.objects.create(up_or_down=up_or_down, myuser=myuser, book=self)
        print(self.get_upvotes)





    def __str__(self):
        return self.title + ' (' + self.author + ')'

    def __repr__(self):
        return self.get_full_title() + ' / ' + self.author + ' / ' + self.type

views.py
def book_detail(request, **kwargs):
    book_id = kwargs['pk']
    book = Book.objects.get(id=book_id)

    # Add comment
    if request.method == 'POST':
        form = CommentForm(request.POST)
        form.instance.myuser = request.user
        form.instance.book = book
        if form.is_valid():
            form.save()
        else:
            print(form.errors)

    comments = Comment.objects.filter(book=book)
    context = {'that_one_book': book,
               'comments_for_that_one_book': comments,
               'upvotes': book.get_upvotes_count(),
               'downvotes': book.get_downvotes_count(),
               'comment_form': CommentForm}
    return render(request, 'book-detail.html', context)


def vote(request, pk: str, up_or_down: str):
    book = Book.objects.get(id=int(pk))
    myuser = request.user
    book.vote(myuser, up_or_down)
    return redirect('book-detail', pk=pk)

【问题讨论】:

  • 如果需要,我也设置了view.py或者models.py
  • 乍一看这一行:{% if that_one_book.get_upvotes_count == 0 and that_one_book.get_downvotes_count == 0%} 如果一本书只有一票,则将对所有人隐藏投票系统。如果您尝试在 views.py 中而不是在模板中实现逻辑,那么在 django 中会好得多。无论如何,如果您共享 models.py 和 views.py 将会很有用
  • 我更新了代码。 models.py 和 view.py 在原帖中。

标签: python-3.x django templates


【解决方案1】:

我觉得我不太理解你的逻辑。 您可以尝试更简单的方法:

0.- 你需要存储投票,所以在你的 Post 类中添加:

post_pos = models.IntegerField(default=0)
post_neg = models.IntegerField(default=0)

1.- 如果用户投票与否,您需要一个存储数据的地方。让我们这样做:

 from django.contrib.auth.models import User

 class UserVote(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,null=True)
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    vote_type = models.CharField(max_length=10)

2.- 现在你需要一个处理逻辑的函数:

从 .models 导入帖子

def positive_post(request, post_id):
    #grab the post and the user
    post = Post.objects.get(pk=post_id)
    user = request.user
    # Now try to find if that user has voted
    try:
        voted = UserVote.objects.get(post=post,user=user)
        # if you can then, user already voted.
        return HttpResponse("YOU ALREADY VOTED")
    except:
        # If u can not, the user didnt vote yet, so 
        # create a new obejct.
        obj = UserVote()
        obj.post = post
        obj.user = user
        obj.vote_type = "positive"
        obj.save()
        # add positive vote to post DB
        post.post_pos += 1
        post.save()
        return redirect("some_place")

3.- 为负面帖子做同样的功能

4.- 创建模板:

<p>
    <a href="{% url 'blog:positive_post' post.id %}">
      VOTE UP {{ post.post_pos}}
  </p>
  <p>
    <a href="{% url 'blog:negative_post' post.id %}">
      VOTE DOWN {{ post.post_neg}}
  </p>

5.- 处理 urls.py:

 from blog.models import views
   
 urlpatterns = [
     path('<int:post_id>/up/',views.positive_post, name='positive_post'),
     path('<int:post_id>/down/',views.negative_post, name='negative_post'),]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多