0

How to get votes data from database without reloading the page?

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'),

]

If I click vote link in the home page, page will reloaded and will get votes result,

How do i stop reloading page.???

I need your help please!.

Osman Hamashool
  • 284
  • 2
  • 16

2 Answers2

0

You tagged this question AJAX but I do not see any of your code? Based off of what you are asking I think that this previously asked question should be able to help you resolve this problem. Particularly the html using django templates and tags and the js section

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>
noes1s
  • 134
  • 7
  • If you run into an issue while using [this previously asked question](https://stackoverflow.com/questions/34774138/reload-table-data-in-django-without-refreshing-the-page), please update your question and I would be glad to take a look at it. – noes1s Oct 18 '17 at 04:21
  • What about now! – Osman Hamashool Oct 18 '17 at 12:41
0

what I understand from your post, is you need to post data through upvote then display or reloading the current voting results from database without redirecting or reloading the page again. if I understood correctly do the following, otherwise leave a comment or update your question.

In 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>

In views.py, don't redirect to home, instead return your response in 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')
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
  • Brother I'm usign django v1.11 and python v3.5, I get error from django.utils import simplejson ImportError: cannot import name "simplejson" – Osman Hamashool Oct 18 '17 at 11:41
  • use serialize instead => from django.core.serializers import serialize then call serialize('json', yourObject) – Muhammad Soliman Oct 18 '17 at 19:42
  • please check again the updated answer, hope it is clear for you now and let me know if you still have any problem – Muhammad Soliman Oct 18 '17 at 19:48
  • Also make sure to put the html elements next to each other exactly as appeared in the answer – Muhammad Soliman Oct 18 '17 at 20:00
  • I get this error (( "POST /upvote/74 HTTP/1.1" 404 2422 )). If I do in HTML like this (( vote )) I will get this error (( "POST /home/upvote/74/ HTTP/1.1" 403 2502 )) ****Forbidden (CSRF token missing or incorrect.): /home/upvote/74/****... what should I do? – Osman Hamashool Oct 20 '17 at 10:50