Django 專案(一個分頁的博客)中有一個視圖負責點贊的作業方式。它有一個缺點:當用戶喜歡一個帖子時,它會被重定向到網站的主頁。我該如何解決這個問題,以便用戶留在他們喜歡的頁面上。
視圖.py
class AddLikeView(View):
def post(self, request, *args, **kwargs):
blog_post_id = int(request.POST.get('blog_post_id'))
user_id = int(request.POST.get('user_id'))
url_from = request.POST.get('url_from')
user_inst = User.objects.get(id=user_id)
blog_post_inst = News.objects.get(id=blog_post_id)
try:
blog_like_inst = BlogLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst)
except Exception as e:
blog_like = BlogLikes(blog_post=blog_post_inst,
liked_by=user_inst,
like=True)
blog_like.save()
return redirect(url_from)
模板.py
<form action="{% if not is_liked_bool %}{% url 'add' %}{% else %}{% url 'remove' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" name="blog_post_id" value="{{ blog_post_id }}">
<input type="hidden" name="user_id" value="{% if user.is_authenticated %}{{ request.user.id }}{% else %}None{% endif %}">
<input type="hidden" name="url_from" value="{{ request.path }}">
{% if is_liked_bool %}
<input type="hidden" name="blog_likes_id" value="{{ blog_likes_id }}">
{% endif %}
<button type="submit" class="btn btn-success">
{% if not is_liked_bool %}
<i class="fi-xnluxl-heart">?</i>
{% else %}
<i class="fi-xnluxl-heart-solid">?</i>
{% endif %}
<span class="likes-qty">{{ likes_counter }}</span>
</button>
uj5u.com熱心網友回復:
我認為您應該先檢查該url_from欄位。只需列印它,如果有誤,您應該更改{{request.path}}模板中的欄位。
你可以試試這個:
{{ request.get_full_path }}
而且,如果我沒記錯的話,您可以request.path在視圖中訪問路徑,而無需通過模板發送路徑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367088.html
