如何使用ajax在Django中实现编辑?

时间:2017-01-19 15:35:12

标签: jquery ajax django

我有一张付款

的表格
<table class="table" id="payments">
    <thead>
        <tr>
            <th>Date</th>
            <th>Description</th>
            <th>Comment</th>
            <th>Amount</th>
            <th>Show</th>
            <th>Edit</th>
            <th>Destroy</th>
        </tr>
    </thead>

    <tbody>
        {% for payment in payments %}
            <tr>
                <td>{{ payment.created_date|date:'Y-m-d H:i' }}</td>
                <td>{{ payment.description }}</td>
                <td>{{ payment.comment }}</td>
                <td>{{ payment.amount }}</td>
                <td><a id="{{ payment.pk }}" class="show_payment">Show</a></td>
                <td><a id="{{ payment.pk }}" class="edit_payment">Edit</a></td>
                <td><a id="{{ payment.pk }}" class="destroy_payment">Destroy</a></td>
            </tr>
        {% endfor %}
    </tbody>
</table>

显示的每个链接都有此付款的ID。当我点击此链接时,我的表单会显示相应付款的预先填写数据,但是当我点击提交时,会创建新的付款。

$(".edit_payment").click(function () {
    var payment_id = $(this).attr('id');
    $.ajax({
        url: '/payment/'+payment_id+'/edit/',
        type: 'get',
        success: function (data) {
            $('#hide_payment').show();
            $("#payments").after(data);
            $('#hide_payment').click(function(){
                $("#payment_form").remove();
                $('#hide_payment').hide();
            });
        }
    });
});

$(document).ready(function(){
    $('#payment_form').hide();
    $('#hide_payment').hide();
    //$("#submit_payment").click(function() {
    var form = $("#payment_form");
    var options = {
        success: function(data){
            // var new_element = $(data).find('tr:last');
            // $("#payments").append(new_element);
            $('#payment_form').hide();
        },
        clearForm: true
    };
    $('#payment_form').on('submit', function() {
        $(this).ajaxSubmit(options);
        return false;
    });
});

但我想编辑此付款而不是创建新的。

def payment_edit(request, pk):
    if request.user.is_authenticated():

        if request.user.has_perm('tracker.admin') or request.user.has_perm('tracker.manager'):
            payment = get_object_or_404(Payment, pk=pk)

            if request.method == "POST":
                form = PaymentForm(request.POST, instance=payment)

                if form.is_valid():
                    payment = form.save(commit=False)
                    payment.save()
                    return redirect('payment_list')
            else:
                form = PaymentForm(instance=payment)
            return render(request, 'tracker/payment_edit.html', {'form': form})

付款方式

class PaymentForm(forms.ModelForm):
    class Meta:
        model = Payment
        fields = ('comment', 'description', 'amount', 'created_date')

1 个答案:

答案 0 :(得分:0)

我只需要重写我的模板:在表单中使用url链接。