如何删除重新加载页面?

时间:2017-10-17 21:11:20

标签: django

如何在不重新加载页面的情况下从数据库获取投票数据?

my models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save


class Post(models.Model):
    post = models.CharField(max_length=500)
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    post_img = models.ImageField(upload_to='posts_img/')
    votes = models.IntegerField(default=0) 

my views.py

def upvote(request, post_id):
    vote = Post.objects.get(pk=post_id)
    vote.votes += 1
    vote.save()
    return redirect('home:home')

my home.html

                {% if post.post_img %}
                    <img class="post-img" src="{{ post.post_img.url }}">
                    <a href="upvote/{{ post.id }}"> vote </a>{{ post.votes }}
                {% endif %}
                <p><i>Posted on <b class="date">{{ post.created }}</b></i</p>

my urls.py

from django.conf.urls import url
from . import views

urlpatterns = [

    url(r'^upvote/(?P<post_id>[0-9]+)/$', views.upvote, name='upvote'),

]

如果我点击主页上的投票链接,页面将重新加载,并将获得投票结果,

如何停止重新加载页面。???

我需要你的帮助!

2 个答案:

答案 0 :(得分:0)

您已将此问题标记为AJAX,但我没有看到您的任何代码?根据您的要求,我认为this previously asked question应该能够帮助您解决此问题。特别是html使用django模板和标签以及js部分

HTML

 <table id="_appendHere" class="table table-striped table-condensed">
      <tr>
        <th>Reg.nr.</th>
        <th>M&auml;rke</th>
        <th>Modell</th>
      </tr>
      {% for i in order %}
        {% if i.order_booked %}
        <tr class="success">
        {% else %}
        <tr>                    
        {% endif %}

         <td>{{ i.regnr|upper }}</td>
         <td>{{ i.brand|capfirst }}</td>
         <td>{{ i.brand_model|capfirst }}</td>
      </tr>
      {% endfor %}
    </table>

JS

<script>
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% url 'get_more_tables' %},  // URL to your view that serves new info
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 10000)
</script>

答案 1 :(得分:0)

我从您的帖子中了解到,您需要通过upvote发布数据,然后显示或重新加载数据库中的当前投票结果,而无需重新定向或重新加载页面。如果我理解正确,请执行以下操作,否则请发表评论或更新您的问题。

home.html

...
...
<a href="#" class="upvote" data-action="/upvote/{{ post.id }}"> vote </a> 
<span class="votes">
{{ post.votes }}
</span>
...
...
<script>
$(".upvote").click(function(e){
  e.preventDefault();
  var $this = $(this);
  var url = $(this).data("action");
  $.post(url, function(response){
   if(response && response.success==true)
      $this.next(".votes").text(response.votes);
  });
});
</script>

views.py中,不要重定向到主页,而是在JSON

中返回您的回复
from django.utils import simplejson
#use the following instead as you use Django 1.11 
from django.core.serializers import serialize

def upvote(request, post_id):
   ...
   ...
   #get votes from database and assign to variable 
   vote = Post.objects.get(pk=post_id)
   votes_from_database = vote.votes
   response_data_to_dump = {
      'success': true,
      'votes': votes_from_database,
   }

   data = simplejson.dumps(response_data_to_dump)
   # use the following instead for Django 1.11 
   data = serialize('json', response_data_to_dump)
   return HttpResponse(data, content_type='application/json')
   #use the following fro Django 1.6 
   #return HttpResponse(data, mimetype='application/json')