django和jQuery - 内联删除和记录更新

时间:2013-02-13 11:40:44

标签: jquery django

我是django的新手,我遇到了一些困难。我有一张包含多个(100个)记录的表格。

我想使用jQuery来启用内联更新和删除记录。

HTML:

<p>The current candidate list is:</p>
    <div id="display1">
        <span>
          <button class="delete_button" id="1">del</button>
        </span>
        <span style="width:50px;">
          <button class="editdiv" id="1">EDIT</button>
        </span>
        <span>
            <a href="/candidates/1/">jake wilmott</a>
        </span>
        <span>
            de vere 
        </span>
        <span>
            Nepal 
        </span>
        <span>
            hands off 
        </span>
        <span>
            connected 
        </span>
        <span>
            nice guy 
        </span>
    </div>
    <div class="noshow" id="edit1">
        <span style="width:100px;"><button class="update" id="1">update</button></span>
        <span>
            jake wilmott
        </span>
        <span style="width:220px;">
            <input class="company" type="textfield" style="width:210px;" id="new_company1" value="de vere" />
        </span>
        <span>
            <input type="text" id="new_country1" value="Nepal" />
        </span>
        <span>
            <select id="new_status1">
                <option value="no contact">no contact</option>
                <option value="hands off">hands off</option>
                <option value="ongoing">ongoing</option>
                <option value="sent email">sent email</option>
                <option value="waiting">waiting</option>
                <option value="trash">trash</option>
            </select>
        </span>
        <span>
            <input type="text" id="new_connection" value="connected" />
        </span>
        <span style="width:220px;">
            <input type="textfield" style="width:210px;" id="new_notes" value="nice guy" />
        </span>
    </div>

jQuery函数是:

//delete
<script>
    $(document).ready(function() {
        $(".delete_button").click(function() {
            alert('delete script')
            var id = $(this).attr('id');
            alert(id)
            $.ajax({
                type: "POST",
                 url: "/candidates/",
                data: { id:id },
                success: function(response){
                    alert(response);
                }
            });
            return false;
        });
    });
</script>

alert('delete script')提醒,alert(id)提醒。但随后它崩溃了,没有任何反应

更新的jQuery是:

<script>
    $(document).ready(function() {
        $('.update').click(function() {
            alert('script now')
            var id = $(this).attr('id');
            var company = $("#new_company" + id).val()
            var country = $("#new_country" + id).val()
            var status =  $("#new_status" + id).val()
            alert(status)
            $.post('/candidates/' + id + company + country + status + '/', function() {
                alert('to here')
                //$this.replaceWith("<span class='success'>Liked</span>");
                jQuery(data["html"]).appendTo(".success");
            });
        });
    });
</script>

再次alert('script now')alert(status)都尽职地提醒,然后再次发生故障。

urls.py是:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    # Examples:
    url(r'^candidates/$', 'candidates.views.index'),
    # url(r'^$', 'amore.views.index', name='index'),
    url(r'^candidates/(?P<id>\d+)/$', 'candidates.views.detail'),
    url(r'^candidates/(?P<id>\d+)/$', 'candidates.views.delete'),
    url(r'^update/(\d+)/$','candidates.views.update'),

views.py是:

from django.template import Context, loader
from candidates.models import Candidates
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404

def index(request):
    return HttpResponse("Hello, world. You're at the candidate index.")

def index(request):
    data = Candidates.objects.all()[:5]
    t = loader.get_template('candidates/index.html')
    c = Context({
        'data': data,
    })
    return HttpResponse(t.render(c))

def update(request, id):
    candidate = Candidates.objects.get(pk = id)
    candidate.company = request.POST.get('company')
    candidate.country = request.POST.get('country')
    candidate.status = request.POST.get('status')
    candidate.notes = request.POST.get('notes')
    candidate.save()
    return HttpResponse('updated')

def delete(request, id):    
    candidate = Candidates.objects.get(pk = id)
    candidate.delete()
    return HttpResponse('this record has been deleted')

def detail(request, id):
    p = get_object_or_404(Candidates, pk=id)
    return render_to_response('candidates/detail.html', {'Candidates': p})

我已经搜索了数百页,但我无法解决这个问题。

所以:

  1. 我做错了什么?
  2. jQuery脚本中的URL应该将变量传递给views.py
  3. urls.py文件是否正确?
  4. 请帮助我让它发挥作用!

2 个答案:

答案 0 :(得分:3)

对于jQuery,您需要以JSON的形式返回答案,而不是HTML。

def delete(request):    
    candidate = Candidates.objects.get(pk = int(request.REQUEST['id']))
    candidate.delete()
    payload = {'success': True}
    return HttpResponse(json.dumps(payload), content_type='application/json')

示例jquery delete

 //delete
 <script>
 $(document).ready(function() {
    $(".delete_button").click(function() {
        alert('delete script')
        var id = $(this).attr('id');
        alert(id)
        $.ajax({
            type: "POST",
            url: "/candidates/delete/",
            data: { id:id },
            success: function(response){
                alert(response.success);
            }
        });
        return false;
    });
});

在urls.py中

url(r'^candidates/delete/$', 'candidates.views.delete'),

答案 1 :(得分:1)

有多个问题

1-正确修复您的网址

url(r'^candidates/(?P<id>\d+)/$', 'candidates.views.detail'),
url(r'^candidates/delete/(?P<id>\d+)/$', 'candidates.views.delete'), #add prefix 'delete'
url(r'^update/(?P<id>\d+)/$','candidates.views.update'),  # add ?P<id>

2-在ajax for delete中,将代码更新为

$.ajax({
    type: "POST",
     url: "/candidates/delete/"+id, //added delete/id in url
    data: { 'id':id },              // quotes around id key

3 - 同样,编写Ajax进行更新,而不是编写方式。样品

$.ajax({
    type: "POST",
     url: "/update/"+id, //added delete/id in url
    data: { 'id':id,             //provide post data
            'company': company,
            'status': status,
            'notes': notes
       },