Django的是,jQuery,Ajax的;刷新div表决系统不工作? [英] Django,Jquery,Ajax; refreshing div for voting system not working?

查看:196
本文介绍了Django的是,jQuery,Ajax的;刷新div表决系统不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作的django投票系统,在数据库中的条目上使用上下按键。



我需要{{entry.score}}刷新该页面没有重新加载,因为页面上将会有其他条目。 {{entry.text}}可以刷新,但需要保持为相同条目,直到不同的按键选择不同的条目。



我试图这样做ajax,但是得到500内部服务器错误,不刷新,

  GET http://127.0.0.1:8000/voteup/ ?voteid = 30 500(INTERNAL SERVER ERROR)jquery.min.js:4 
发送jquery.min.js:4
n.extend.ajax jquery.min.js:4
n (匿名函数)jquery.min.js:4
(匿名函数)(索引):76
n.event.dispatch jquery.min.js:3
r.handle

即使投票正确执行...



(index):76在voting.html是:$ .get(/ voteup /,args).done(function(data){



voting.html

 < div class =table> 
< div id =Voteclass =vote>
< div style =text-align:left>
{percent for entries in voting_entry_list%}
< li>< ; href =/ entries / {{entry.id} } /> {{entry.text}}& nbsp {{entry.score}}< / a>< / li>
< p>
< input type =submitid =voteidname ='voteid'value ={{entry.id}}autofocus value =onfocus =this.value = this.value; class =transparent/>
< script>
var data ='#Vote';
var url =/ voting /;
$(document).ready(function(){
$(#voteid)bind(keydown,function(e){//输入#submit ???
if(e.keyCode == 38){
var text = $(#voteid)。val();
var args = {'voteid':text};
$ .get(/ voteup /,args).done(function(data){
console.log(message:+ data);
$ .ajax({
url :
data:data,
dataType:'html',
success:function(data){
$(this).html(data); // this?
}
});
});
return false;
}
});
});
< / script>
{%endfor%}
< / div>
< / div>
< / div>

views.py



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $((((((((((((((((((((((((((((((((((((((((((( )
}
return render(request,'entries / index.html',context);

def投票(请求):
上下文= {'voting_entry_list':Entry.objects.random(),}
return render(request,'entries / voting.html' ,上下文);

def voteup(request):
voting_id = request.GET.get('voteid')
e = Entry.objects.unvoted_or_random()
context = {' vot_entry_list':e,}
如果request.method =='GET':
v = Entry.objects.get(pk = voting_id)
v.score + = 1
v .voted = True
v.save()
context = {'voting_entry_list':v,}
else:
pass
return render(request,'entries / voting.html',上下文);

Models.py

  class EntryManager(models.Manager):#a基本扩展模型basemanager插入新排序
def unvoted_or_random(self):#命令定义使用模型输入
unvoted_entries = self.filter(voted = False).order_by(' - pub_date')#从任何用户的最年轻的未注册条目排序
voted_entries = self.filter(voted = True).order_by('?' )#如果没有未注册的条目,voteed boolean启用随机选择'?'
如果unvoted_entries:#for boolean unvoted
return unvoted_entries [:1]#return latest
else:#for boolean voted
return voted_entries [:1]#return random


解决方案

我刚刚和大学的博士生进行了一次会议,他把我放在正确的轨道上。



我所遇到的基本问题是使用哲学Jquery和Ajax,事情g我很难从手册和在线支持中收集到,我发现在简单任务的基础上是不透明的。为此,我将在此介绍最终的代码,希望它可以帮助人们以类似的简单投票系统开始。



感谢使用JQuery和AJAX刷新Django中的div 在Django上的Ajax中重载整个页面 如何使用Jquery正确刷新div / Django模板中的Ajax 通过jQuery ajax调用将值列表传递给django视图
对于位和块...






没有更改条目的投票刷新(按钮交换)






我的主要问题是我为url和数据做了什么。事实证明我的棍子结束了错误。在我的情况下的数据是从视图.get的返回(我认为这是我必须传递到刷新的条目id),我不需要为我制作的非常简单的系统定义url。



所以这样:



voting.html

  var data ='#Vote'; 
var url =/ voting /;

$ .ajax({
url:url,
data:data,
dataType:'html',
success:function(data){
$(this).html(data);
}

成为这个:

  $(#score)。text(data); // span updates score从视图中获得新的值

刷新分数,因为它们被投票。代码允许我访问分数:

 < span id =score> {{entry.score}}< ; / span> 

我唯一需要做的就是将其添加到投票视图中请求)或投票(请求),当我访问条目模型并添加投票:



views.py

  return HttpResponse(v.score)

这是上下投票,当你按下上下箭头的时候,条目保持不变,但是投票在保存到数据库后重新刷新视图。






em>






要将条目(新的随机条目)更改为右箭头键返回一个带有随机条目的id,文本和分数的字符串;



views.py

  def random_entry(request):
e = Entry.objects.random()[0]
return HttpResponse(%s,% s,%s%(e.id,e.text,e.score))

其中voting.html拆分和刷新文本和分数,并更改currentid:



voting.html

  if(e.keyCode == 39){//右键
$ .get(/ random-entry /,{})。done function(data){
var parts = data.split(,);
$(#entry-text)。text(parts [1]);
$(#score)。text(parts [2]);
currentid = parts [0];
console.log(random entry data:+ data);
});
return false;}

所以这是主要的变化。我包含下面的完整的(ish)代码,希望它能帮助某人;



voting.html

 < div class =table> 
< div id =Voteclass =vote>
< div style =text-align:left>
{%for entries in voting_entry%}
< li>< a href =/ entries / {{entry.id}} />< span id =entry-text > {{entry.text}}< / span> < span id =score> {{entry.score}}< / span>< / a>< / li>
< p>
< input type =submitid =voteidname ='voteid'value ={{entry.id}}autofocus value =onfocus =this.value = this.value; class =transparent/>
< script>
$(document).ready(function(){
var currentid = {{entry.id}}; //条目id被定义
$(#voteid)bind keydown,function(e){
if(e.keyCode == 38){//向上箭头键
var args = {'voteid':currentid}; //当前使用的ID
$ .get(/ voteup /,args).done(function(data){//当.get完成后,从视图(score)返回数据
console.log(message: +数据);
$(#score)。文本(数据); //从视图获得新值的更新
});
返回false;
}
if(e.keyCode == 40){//向下箭头键
var args = {'voteid':currentid}; //使用当前id
$ .get(/ voteed /,args).done(function(data){// when .get完成后,从视图返回数据(score)
conso le.log(message:+ data);
$(#score)。text(data); // span updates score with new value from views
});
返回false;
}
if(e.keyCode == 39){//右键
$ .get(/ random-entry /,{})done(function(data){
var parts = data.split(,);
$(#entry-text)。text(parts [1]);
$(#score)。 text(parts [2]);
currentid = parts [0];
console.log(random entry data:+ data);
});
返回false;
}
});
});
< / script>
{%endfor%}
< / div>
< / div>
< / div>



从django.shortcuts导入render 
从django.http导入HttpResponse,HttpResponseRedirect
from entries.models import条目
from datetime import datetime
from django.utils import timezone
from django.views.decorators.csrf import csrf_protect

def index(request ):
context = {
'latest_entry_list':Entry.objects.order_by(' - pub_date')[:10],
'high_entry_list':Entry.objects.order_by(' - score ',' - pub_date')[:10],
'high_entry':Entry.objects.order_by(' - score',' - pub_date')[:1],
'low_entry_list' .objects.order_by('score',' - pub_date')[:10],
'voting_entry':Entry.objects.unvoted_or_random(),
}
return render(request, entries / index.html',context);

def add(request):
created_date = default = datetime.now()
created_text = request.GET.get('text')
e = Entry text = created_text,pub_date = created_date)
e.save()
return HttpResponse('done')

def enter(request):
return render ,'entries / enter.html');

def top(request):
context = {
'high_entry':Entry.objects.order_by(' - score',' - pub_date')[:1]
}
return render(request,'entries / top.html',context);

def投票(请求):
上下文= {'voting_entry':Entry.objects.random(),}
return render(request,'entries / voting.html' ,上下文);

def random_entry(request):
e = Entry.objects.random()[0]
return HttpResponse(%s,%s,%s% id,e.text,e.score))

def voteup(request):
voting_id = request.GET.get('voteid')
if request.method = ='GET':
v = Entry.objects.get(pk = voting_id)
v.score + = 1
v.voted = True
v.save()
return HttpResponse(v.score)
else:
pass
return HttpResponse('done')

def votedown(request):
voting_id = request.GET.get('voteid')
如果request.method =='GET':
v = Entry.objects.get(pk = voting_id)
v.score - = 1
v.voted = True
v.save()
return HttpResponse(v.score)
else:
pass
return HttpResponse('done' )


I have a working django voting system using up and down keypresses on entries in a database.

I need to have the {{ entry.score }} refresh on the page without a reload, as there will be other entries on the page. The {{ entry.text }} can refresh but needs to stay as the same entry until a different keypress selects a different entry.

I'm trying to do it with ajax, but get a 500 Internal Server Error and no refresh,

GET http://127.0.0.1:8000/voteup/?voteid=30 500 (INTERNAL SERVER ERROR) jquery.min.js:4
send jquery.min.js:4
n.extend.ajax jquery.min.js:4
n.(anonymous function) jquery.min.js:4
(anonymous function) (index):76
n.event.dispatch jquery.min.js:3
r.handle

even though the vote goes through correctly...

(index):76 in voting.html is: $.get("/voteup/", args).done(function(data) {

voting.html

 <div class = "table">
  <div id="Vote" class = "vote">
  <div style="text-align: left">
  {% for entry in voting_entry_list %} 
    <li><a href="/entries/{{ entry.id }}/">{{ entry.text }}&nbsp{{ entry.score }}</a></li>
    <p>
    <input type="submit" id="voteid" name='voteid' value="{{ entry.id }}" autofocus value="" onfocus="this.value = this.value;" class = "transparent"/>
          <script>
          var data = '#Vote';
          var url = "/voting/";
            $(document).ready(function() {
              $("#voteid").bind("keydown", function(e) { //input #submit?????
                if (e.keyCode == 38) {
                  var text = $("#voteid").val();        
                  var args = {'voteid':text};       
                  $.get("/voteup/", args).done(function(data) {
                    console.log("message: " + data);
                        $.ajax({      
                            url: url,
                            data: data,
                            dataType: 'html',
                            success: function(data){
                                $(this).html(data); //this?
                            }   
                        });
                  });
                return false;
                }       
              });
            });     
          </script>
     {% endfor %}
      </div>
      </div>
  </div>

views.py

def index(request):   
   context = { # actually one item, command from extended object manager
     'voting_entry_list': Entry.objects.unvoted_or_random(), 
   }     
   return render(request, 'entries/index.html', context); 

def voting(request):
    context = {'voting_entry_list': Entry.objects.random(),}      
    return render(request, 'entries/voting.html', context);

def voteup(request):
    voting_id = request.GET.get('voteid') 
    e = Entry.objects.unvoted_or_random()
    context = {'voting_entry_list': e,}
  if request.method=='GET':
    v = Entry.objects.get(pk=voting_id)
    v.score +=1 
    v.voted=True 
    v.save() 
    context = {'voting_entry_list': v,}
  else:
    pass
  return render(request, 'entries/voting.html', context);

Models.py

class EntryManager(models.Manager): #a basic extention to the model basemanager to insert new sorting
def unvoted_or_random(self): # command definition uses models input
    unvoted_entries = self.filter(voted = False).order_by('-pub_date') # sorted by youngest unvoted entries from any user
    voted_entries = self.filter(voted = True).order_by('?') # if no unvoted entries, voted boolean enables random selection '?'  
    if unvoted_entries: # for boolean unvoted
        return unvoted_entries[:1] # return latest
    else: # for boolean voted
        return voted_entries[:1] # return random

解决方案

I just had a session with a Phd student at the University, and he put me on the right track.

The basic issue I was having was about the philosophy of using Jquery and Ajax, something I found hard to glean from manuals and online support, which I found to be opaque on the very basics for simple tasks. To that end, I will present the final code here in the hopes it helps people starting out with a similar simple voting system.

Thanks to Refresh a div in Django using JQuery and AJAX Reload entire page in Ajax on Django? How to correctly refresh a div using Jquery/Ajax in a Django template Passing list of values to django view via jQuery ajax call For bits and pieces...


Voting refresh with no change of entry (button mashing)


My main problem was what I did for the url and data. It turns out I had the wrong end of the stick. Data in my case is the return from the views .get (I thought it was the entry id that I had to pass to the refresh) , and I didn't need to define the url for the very simple system I was making.

So This:

voting.html

var data = '#Vote';
var url = "/voting/";

$.ajax({      
     url: url,
     data: data,
     dataType: 'html',
     success: function(data){
     $(this).html(data);
  } 

Became This:

$("#score").text(data); //span updates score with new value from views

To refresh the scores as they are voted on. Span in the href above that code allowed me to access the score:

<span id="score">{{ entry.score }}</span>

And the only other thing I had to do was add this to views in voteup(request) or votedown(request) when I accessed the entry models and added the vote:

views.py

return HttpResponse(v.score)

This takes care of the vote up and down. When you button mash the up and down arrows, the entry stays the same, but the votes are refreshed from views after being saved to database.


Key to change entry with refresh


To change the entry (to a new, random entry), the .get for the right arrow key returns a string with the id, text and score of a random entry;

views.py

def random_entry(request):
e = Entry.objects.random()[0]
return HttpResponse("%s,%s,%s" % (e.id, e.text, e.score))

Which voting.html splits and refreshes text and score, and changes the currentid:

voting.html

if(e.keyCode == 39) { //right key
     $.get("/random-entry/", {}).done(function(data) {
         var parts = data.split(",");
          $("#entry-text").text(parts[1]);
          $("#score").text(parts[2]);
          currentid = parts[0];
          console.log("random entry data: " + data);
         });
        return false;}

So that's the main changes. I include the full(ish) code below in hope it helps someone;

voting.html

 <div class = "table">
  <div id="Vote" class = "vote">
  <div style="text-align: left">
  {% for entry in voting_entry %} 
    <li><a href="/entries/{{ entry.id }}/"><span id="entry-text">{{ entry.text }}</span> <span id="score">{{ entry.score }}</span></a></li>
    <p>
    <input type="submit" id="voteid" name='voteid' value="{{ entry.id }}" autofocus value="" onfocus="this.value = this.value;" class = "transparent"/>
          <script>
            $(document).ready(function() {
            var currentid = {{entry.id}}; //entry id is defined
              $("#voteid").bind("keydown", function(e) {
                if (e.keyCode == 38) {  //up arrow key
                  var args = {'voteid':currentid }; //current id is used
                  $.get("/voteup/", args).done(function(data) { //when .get is done, returns data from views(score)                   
                    console.log("message: " + data);
                    $("#score").text(data); //span updates score with new value from views
                  });
                return false;
                }
                if (e.keyCode == 40) { //down arrow key
                  var args = {'voteid':currentid };     //current id is used
                  $.get("/votedown/", args).done(function(data) { //when .get is done, returns data from views(score)
                    console.log("message: " + data);  
                    $("#score").text(data); //span updates score with new value from views
                  });
                return false;
                }
                if(e.keyCode == 39) { //right key
                  $.get("/random-entry/", {}).done(function(data) {
                    var parts = data.split(",");
                    $("#entry-text").text(parts[1]);
                    $("#score").text(parts[2]);
                    currentid = parts[0];
                    console.log("random entry data: " + data);
                  });
                 return false; 
                 }      
              });
            });     
          </script>
     {% endfor %}
      </div>
      </div>
  </div>    

views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from entries.models import Entry
from datetime import datetime
from django.utils import timezone
from django.views.decorators.csrf import csrf_protect

def index(request):   
 context = {
  'latest_entry_list': Entry.objects.order_by('-pub_date')[:10],
  'high_entry_list': Entry.objects.order_by('-score','-pub_date')[:10],
  'high_entry': Entry.objects.order_by('-score','-pub_date')[:1],
  'low_entry_list': Entry.objects.order_by('score','-pub_date')[:10],
  'voting_entry': Entry.objects.unvoted_or_random(),
 }
 return render(request, 'entries/index.html', context);

def add(request):
 created_date = default=datetime.now()
 created_text = request.GET.get('text')    
 e = Entry(text=created_text,pub_date=created_date) 
 e.save()       
 return HttpResponse('done')

def enter(request):
 return render(request, 'entries/enter.html'); 

def top(request):
 context = {
  'high_entry': Entry.objects.order_by('-score','-pub_date')[:1],
 }
 return render(request, 'entries/top.html', context);

def voting(request):
 context = {'voting_entry': Entry.objects.random(),}      
 return render(request, 'entries/voting.html', context);

def random_entry(request):
 e = Entry.objects.random()[0]
 return HttpResponse("%s,%s,%s" % (e.id, e.text, e.score))

def voteup(request):
 voting_id = request.GET.get('voteid')
 if request.method=='GET':
    v = Entry.objects.get(pk=voting_id)
    v.score +=1
    v.voted=True
    v.save()
    return HttpResponse(v.score)
 else:
    pass
 return HttpResponse('done')   

def votedown(request):
 voting_id = request.GET.get('voteid')
 if request.method=='GET':
    v = Entry.objects.get(pk=voting_id)
    v.score -=1
    v.voted=True
    v.save()
    return HttpResponse(v.score)
 else:
    pass
 return HttpResponse('done')

这篇关于Django的是,jQuery,Ajax的;刷新div表决系统不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆