简体   繁体   English

如何将ajax调用应用于DJANGO中的所有模型对象

[英]How to apply ajax call to all model objects in DJANGO

I need to implement AJAX and its working fine. 我需要实现AJAX及其正常工作。 However, I am having problem in applying ajax to each instance of a model. 但是,我在将ajax应用于模型的每个实例时遇到问题。 It's just being applied on the top Object and applying ajax call on the same page. 它只是应用在顶部的Object上,并且在同一页面上应用了ajax调用。 For remaining objects, when I click on the link its directing me to new page and showing me JSON objects which I dont want. 对于其余的对象,当我单击链接时,它会将我定向到新页面并向我显示不需要的JSON对象。

Views.py Views.py

def upvote(request, post_id):

if request.method == "POST":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    return JsonResponse({'count':p.upvote })

if request.method == "GET":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    data = {
        'count' : p.upvote,
    }
    return JsonResponse({'count': p.upvote})

Urls.py Urls.py

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

Views.html Views.html

<script>
    $(function(){
       $('#up_vote').click(function(e) {
          e.preventDefault();
          window.alert("hello");
          console.log("hello");


          $.ajax({
            url: $(this).attr('href'),
            type :'get' ,
            success : function (data){
              // alert('success');
              $('#upvote_count').html(data.count);
            },
            failure : function (data){
              alert('failure') ; 
            }
          }) ;  // ajax call 

       }); // upvote link call
</script>

<div id="columns">
    {% for post in object_list %}

        <div class="pin">
            <a href="/posts/{{ post.id }}/">

            <img src= "/static/media/{{post.image}}" />
            </a>
            <p>
                {{post.description}}
                (<a href="{% url "post-edit" pk=post.id %}">edit</a>)
            </p>


            <div style="float:left">
              <a href='{% url 'upvote-detail' post.id %}' id='up_vote'>Up vote  </a>
              <span id='upvote_count'> {{ post.upvote }} </span> 
            </div>


            <div style="float:right">
              <a href='{% url 'downvote-detail' post.id %}' id='down_vote'> Down vote </a>
              <span id='downvote_count'>{{post.downvote}}</span>
            </div>


        </div>
    {% endfor %}

    </div>

Here is my all the files. 这是我的所有文件。 Currently AJAX call is working absolutely fine. 目前,AJAX呼叫工作正常。 Its just applying on the top (first) of object in for LOOP. 它仅适用于对象的顶部(第一个)。 For Remaining objects, when I click on link, it render me to new page. 对于其余对象,当我单击链接时,它使我进入新页面。 Could someone identify the problem? 有人可以找出问题所在吗? Thanks, 谢谢,

in views.py 在views.py中

def detail(request):
    return render(request, 'detail.html', {'posts': Post.objects.all()})

def upvote(request, post_id):
   if request.method == "POST":
       p = get_object_or_404(Post, pk=post_id)
       p.upvote += 1
       p.save()
       return JsonResponse({'count':p.upvote })
   return JsonResponse({})

in detail.html: detail.html:

{% for post in posts %}
     <a href='{% url 'upvote-detail' post.id %}' id='up_voite'>Up voite <span id='voite_count'> {{ post.upvote }} </span> </a>
 {% endfor %}

<script>
    $(function(){
       $('#up_voite').click(function(e) {
          e.preventDefault();
          $.post($(this).attr('href'), function(data) {
              $(this).find('span').html(data.upvote);
          });
       });
    });
</script>

code is not checked 代码未检查

Try this: 尝试这个:

def upvote(request, post_id):
    p = get_object_or_404(Post, pk=post_id)
    errors = []
    data = {}
    try:
        p.upvote += 1
        p.save()
        data = {
            'success': 1,
        }
    except:
        errors.append(['There was an error'])
        data = {
            'success': 0,
            'errors':errors,
        }
    return HttpResponse(json.dumps(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM