将数据从模板传递到django的views.py

时间:2020-04-14 18:59:34

标签: javascript python jquery html django

现在,我正在django项目中对数据表进行分页。我试图让用户放置每页显示多少个寄存器,但是我在将要使用的选择器中的数字传递给views.py(分页位置)时遇到了麻烦,我的问题是:如何将选定的号码传递给views.py,以更新寄存器?

这是我的代码:

模板的选择器:

<form action="" method="POST">
    <select class="selector" id="estado" name="estado" onchange="post()" style="border-color: #C9C9C9; color:black; height: 25px; width:100px; position:absolute; margin-top:-32px; margin-left:230px;">
        <option  selected style="color:black;">5</option>
        <option   style="color:black;">10</option>
        <option  style="color:black;">25</option>
        <option  style="color:black;">50</option>
        <option  style="color:black;">100</option>
    </select>
</form>

Views.py:

 if request.method == 'POST':
        inicial = { 'paginas' : 5,
        }
        num = paginaForm(initial = inicial).fields['paginas']
    else:
        num = 5

    riesgos = Riesgos.objects.all() 
    #Paginación  
    paginator = Paginator(riesgos, num)
    page = request.GET.get('page')
    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        items = paginator.page(1)
    except EmptyPage:
        paginator.page(paginator.num_pages)
    index = items.number - 1
    max_index = len(paginator.page_range)
    start_index = index - 5 if index >= 5 else 0
    end_index = index + 5 if index <= max_index - 5 else max_index
    page_range = paginator.page_range[start_index:end_index]
    context = {'riesgos':riesgos, 'page_range':page_range, 'items':items}
    return render(request,'restapi/listar_riesgo.html', context)

Models.py

class Paginas(models.Model):
    paginas = models.IntegerField(primary_key= True)

Forms.py:

class paginaForm(forms.ModelForm):
    class Meta:
        model = Paginas
        fields = [ 
            'paginas',
        ]

谢谢大家!

0 个答案:

没有答案