如何防止在Django中使用不同数据加载相同模板时,网址发生变化

2024-06-01 22:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的def,有这样的东西

def policies_index(request):
    """Resource listing"""
    policies = Policy.objects.all()
    context = {
        'policies' : policies
    }
    return render(request, "policies/index.html", context)

现在我想添加一种方法,使用月份和年份过滤这些信息,所以我制作了一个类似这样的函数

def policies_date_filter(request):
    """List the resources based on a month year filter"""
    today = datetime.date.today()
    year = request.POST['year']
    month = request.POST['month']
    policies = Policy.objects.filter(end_date__year=year).filter(end_date__month=month)
    status = settings.POLICY_STATUS_SELECT
    for policy in policies:
        for status_name in status:
            if status_name['value'] == policy.status:
                policy.status_name = status_name['name']
    request.policies = policies

    return policies_index(request)

这样我就可以重用函数索引,避免编写再次打印视图的代码,而且效果很好,但是在url中,而不是像“/policies”这样的内容,我得到了像“/policies/datefilter”这样的内容

这是有意义的,因为我调用了另一个函数。有没有办法防止url更改


Tags: 函数namedateindexobjectsrequestdefstatus
1条回答
网友
1楼 · 发布于 2024-06-01 22:51:05

哈哈,在写这个问题的时候,我发现我可以在视图中调用相同的函数,但是使用POST方法而不是GET,这样他们就可以保持相同的url,所以我最终得到了这样的结果

 def policies_index(request):
    """Resource listing"""

    #If method == POST it means is the filter function so I change the policies queryset
    if request.method == "POST":
        year = request.POST['year']
        month = request.POST['month']
        policies = Policy.objects.filter(end_date__year=year).filter(end_date__month=month)
    else:
        policies = Policy.objects.all()

    context = {
        'policies' : policies,
    }
    return render(request, "policies/index.html", context)

现在就像一个符咒,你们觉得呢?有更好的方法吗?我对Django有点陌生

相关问题 更多 >