事件发生后如何使页面重定向到同一页面

如何解决事件发生后如何使页面重定向到同一页面

我正在尝试在我的网站上制作一个赞成和反对功能。但是有一个我不喜欢的特定行为,即每当用户单击按钮时,他都不应该重定向到另一个页面,而应该保留在同一页面上。

点击 upVote 按钮后会发生什么,它转到了我不想要的 url http://localhost:8001/upVote/2/。我希望它保持在 http://localhost:8001/view-supplier/

的同一页面

models.py

class User(AbstractBaseUser,PermissionsMixin):
    email = models.EmailField(max_length=254,unique=True)

    # CUSTOM USER FIELDS
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    upVotes = models.IntegerField(default=0)
    downVotes = models.IntegerField(default=0)
    objects = UserManager()

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)
        
    def get_email(self):
        return self.email

views.py

def Viewsupplier(request):
    title = "All suppliers"
    suppliers = User.objects.filter(user_type__is_supplier=True)

    context = {"suppliers":suppliers,"title":title}

    return render(request,'core/view-suppliers.html',context)

@login_required
def upVote(request,pk):
    supplier_Vote = get_object_or_404(User,id=pk)
    supplier_Vote.upVotes += 1
    supplier_Vote.save()
    upVote_count = supplier_Vote.upVotes
    context = {"supplier_Vote":supplier_Vote,"upVote_count":upVote_count}
    return render(request,"core/view-suppliers.html",context)

@login_required
def downVote(request,id=pk)
    supplier_Vote.downVotes -= 1
    supplier_Vote.save()
    downVote_count = supplier_Vote.downVotes
    context = {"supplier_Vote":supplier_Vote,"downVote_count":downVote_count}
    return render(request,context)

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('upVote/<int:pk>/',views.upVote,name='upVote'),path('downVote/<int:pk>/',views.downVote,name='downVote'),]

查看供应商.html

<table class="table table-borderless table-data3">
    <thead>
        <tr>
            <th>No</th>
            <th>Country</th>
            <th>Votes</th>
        </tr>
    </thead>
    <tbody>
        {% for supplier in suppliers %}
        <tr>
            <td>{{forloop.counter}}</td>
            <td>{{supplier.country}}</td>
            <td>
                <div class="table-data-feature">
                    <a href="{% url 'upVote' supplier.id %}" class="m-r-10">
                        <button class="item" data-toggle="tooltip" data-placement="top" title="Like">
                        <i class="zmdi zmdi-thumb-up"></i>{{upVote_count}}</button>
                    </a>
                    <a href="{% url 'downVote' supplier.id %}">
                        <button class="item" data-toggle="tooltip" data-placement="top" title="dislike">
                        <i class="zmdi zmdi-thumb-down"></i>{{downVote_count}}</button>
                    </a>
                </div>
            </td>
        </tr>
        {% empty %}
            <tr><td class="text-center p-5" colspan="7"><h4>No supplier available</h4></td></tr>
        {% endfor %}
    </tbody>
</table>

解决方法

您需要实现一个 API(应用程序编程接口)来异步发送赞成票和反对票。 Django REST framework 是创建您自己的 API 的方法。您可以在 YouTube 上观看有关该主题的数小时视频教程。 Django REST framework 的文档非常好,也很容易阅读。 Django 是一个服务器端的 web 框架,这意味着它只有在你提交到服务器时才能帮助你。您绝对可以重新加载同一页面:

return HttpResponseRedirect(reverse('<app_name>:<url_name>'))

但是,会有中断。因此,处理此类行为的推荐方法是使用 JavaScript 的 API(例如 Fetch API)异步调用 REST 框架。

如果您可能出于对学习异步编码的错误恐惧而决定以老式的方式将数据发送到您的服务器,您可以随时使用您的赞成和反对意见来提交用户数据并更新计数。然后,在您的 view_supplier 视图中,您需要获取更新的视图计数并将其传递给上下文。因此,您的 upvote 视图会更改 upvote 计数并触发 Viewsupplier 视图。然后,在 ViewSupplier 视图中,您获取计数并将其添加到上下文中

# in your template
<a href="{% url 'upvote' supplier.id %}" class="m-r-10">
   <button class="item" data-toggle="tooltip" data-placement="top" title="Like">
   <i class="zmdi zmdi-thumb-up"></i>{{upvote_count}}</button>
</a>

# in your view
def Viewsupplier(request):
    title = "All Suppliers"
    suppliers = User.objects.filter(user_type__is_supplier=True)

    # Get the updated count:
    suppliers_votes_count = {}
    for supplier in suppliers:
        upvote_count    = supplier.upvotes
        downvote_count  = supplier.upvotes

        supplier_count = {supplier: {'upvote': upvote_count,'downvote': downvote_count } }
    
    suppliers_votes_count.update(supplier_count)

    context = {"suppliers":suppliers,"title":title,"suppliers_votes_count": suppliers_votes_count }

    return render(request,'core/view-suppliers.html',context)

@login_required
def upvote(request,pk):
    supplier_vote = get_object_or_404(User,id=pk)
    supplier_vote.upvotes += 1
    supplier_vote.save()
    upvote_count = supplier_vote.upvotes
    context = {"supplier_vote":supplier_vote,"upvote_count":upvote_count}
    return HttpResponseRedirect(reverse('core:view_supplier'))
,

这可以通过使用 AJAX 轻松实现。

与其提供 where d.ScheduledDate >= DateTime.Today.AddDays(-1095) 作为 URL 的一部分,不如将 AJAX 中的 supplier_id 发送到您的 Django Upvote 视图。你可以这样做。

HTML:

supplier_id

使用 Javascript 从点击事件的按钮中提取 <button id="{{ supplier_id }}" class="item upvote" data-toggle="tooltip" data-placement="top" title="Like"> <i class="zmdi zmdi-thumb-up"></i>{{upvote_count}} </button>

JavaScript:

supplier_id

将 Django urls.py 中的 url 模式更改为

$('.upvote').on('click',function () { var supp_id = $(this).attr('id'); $ajax({ type: 'POST',url: '/upvote/',data: { supplier_id: supplier_id,},success: function (data) { if (data.status == 'success') { /* Your upvote logic like updating the color of button or showing Unlike etc.,*/ } } }); });

Views.py

urlpatterns = [path('upvote/',views.upvote,name='upvote'),

同样,您可以对 def upvote(request): if request.method == 'POST': supplier_id = request.POST['supplier_id'] # Your DB update logic goes here.... return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'Error'}) 执行相同的操作。

,

以下是我将如何实现这一目标:

首先我有简单的表单来处理赞成票/反对票:

<form method="POST" action="{% url 'view-supplier' %}"> //upvote form
  {% csrf_token %}
  <input type="hidden" name="upvote-button">
  <button type="submit" style="width:100%">Upvote Button</button>
</form>

<form method="POST" action="{% url 'view-supplier' %}"> // downvote form
  {% csrf_token %}
  <input type="hidden" name="downvote-button">
  <button type="submit" style="width:100%">Downvote Button</button>
</form>

然后我将视图设置为:

def supplierView(request):
   supplier_vote = get_object_or_404(User,id=pk)

   if 'upvote-button' in request.POST:
         supplier_vote.upvotes += 1
         supplier_vote.save()
         upvote_count = supplier_vote.upvotes

   elif 'downvote-button' in request.POST:
         supplier_vote.downvotes -= 1
         supplier_vote.save()
         downvote_count = supplier_vote.downvotes
   
   else:
         downvote_count = supplier_vote.downvotes
         upvote_count = supplier_vote.upvotes

   context = {
    'upvote_count': upvote_count,'downvote_count': upvote_count,}

   return render(request,'main/view-suppliers.html',context)

这样,当有人点击 upvote 按钮时,他们被重定向到同一个视图,然后处理添加 upvote 并更新上下文。

如果 view-supplier 是详细视图,您还必须将 PK 传递给视图。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?