django fbv AJAX与分页

时间:2017-07-25 21:16:59

标签: ajax django pagination

我正在尝试使用带分页的AJAX创建一个CRUD,但是当我尝试添加一本新书时,我在foreach书中得到了异常空白,但是当我刷新页面时它工作并显示新的寄存器。 / p>

views.py:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def livro(request):
    livros = Livro.objects.all().order_by('-id')
    paginator = Paginator(livros, 5)

    page = request.GET.get('page', 1)
    try:
        registers = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        registers = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        registers = paginator.page(paginator.num_pages)

    return render(request, 'livros.html', {'registers': registers})

def salvar_form_livro(request, form, template_name):
    data = dict()
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            #import pdb; pdb.set_trace()
            livros = Livro.objects.all().order_by('-id')
            data['html_book_list'] = render_to_string('listaLivros.html', {
                'livros': livros
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)

def criarLivro(request):
    if request.method == 'POST':
        form = LivroForm(request.POST)
    else:
        form = LivroForm()
    return salvar_form_livro(request, form, 'cadastraLivro.html')

template.html

{% for livro in registers %}
    <tr>
        <td>{{ livro.id }}</td>
        <td>{{ livro.titulo }}</td>
        <td>{{ livro.autor }}</td>
        <td>{{ livro.get_tipoLivro_display }}</td>
        <td>{{ livro.dataPublicacao }}</td>
        <td>{{ livro.paginas }}</td>
        <td>{{ livro.preco }}</td>
        <td>
            <button type="button"
                    class="btn btn-warning btn-sm js-update-book"
                    data-url="{% url 'livro_alterar' livro.id %}">
                    <span class="glyphicon glyphicon-pencil"></span> Alterar
            </button>
            <button type="button"
                    class="btn btn-danger btn-sm js-delete-book"
                    data-url="{% url 'livro_deletar' livro.id %}">
                    <span class="glyphicon glyphicon-trash"></span> Deletar
            </button>
        </td>
    </tr>
{% empty %}
    <tr>
        <td colspan="7" class="text-center bg-warning">Não há livros cadastrados</td>
    </tr>
{% endfor %}

index.js:

$(function () {

    /* Functions */

    var loadForm = function () {
        var btn = $(this);
        $.ajax({
            url: btn.attr("data-url"),
            type: 'get',
            dataType: 'json',
            beforeSend: function () {
                $("#modal-book").modal("show");
            },
            success: function (data) {
                $("#modal-book .modal-content").html(data.html_form);
            }
        });
    };

    var saveForm = function () {
        var form = $(this);
        $.ajax({
            url: form.attr("action"),
            data: form.serialize(),
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (data.form_is_valid) {
                    $("#book-table tbody").html(data.html_book_list);
                    $("#modal-book").modal("hide");
                }
                else {
                    $("#modal-book .modal-content").html(data.html_form);
                }
            }
        });
        return false;
    };


    /* Binding */

    // Create book
    $(".js-create-book").click(loadForm);
    $("#modal-book").on("submit", ".js-book-create-form", saveForm);

    // Update book
    $("#book-table").on("click", ".js-update-book", loadForm);
    $("#modal-book").on("submit", ".js-book-update-form", saveForm);

    // Delete book
    $("#book-table").on("click", ".js-delete-book", loadForm);
    $("#modal-book").on("submit", ".js-book-delete-form", saveForm);

});

结果:

When I add a new register return that are no registers And when I refresh the page the result are here

0 个答案:

没有答案