简体   繁体   English

在 Django 中加载具有不同数据的相同模板时如何防止 url 更改

[英]How to prevent a url from changing when loading the same template with different data in Django

I got a simple def with something like this我得到了一个简单的 def 类似这样的东西

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

now I want to add a way to filter that info using month and year so I made a function like this现在我想添加一种使用月份和年份过滤该信息的方法,所以我做了一个这样的功能

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)

that way I can reuse the function index to avoid writing the code to print the view again and works perfect, but in the url instead of something like "/policies" I got something like "/policies/date-filter"这样我就可以重用函数索引以避免编写代码来再次打印视图并且工作完美,但是在 url 而不是像“/policies”这样的东西我得到了像“/policies/date-filter”这样的东西

Which makes sense since Im calling another function Is there a way to prevent the url from changing?这是有道理的,因为我正在调用另一个函数 有没有办法防止 url 改变?

lol, writing this question I just figured it out I could call the same function in the view but with a POST method instead of a GET so they will keep the same url, so I ended up with something like this大声笑,写这个问题我刚刚发现我可以在视图中调用相同的函数,但是使用 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)

and now works like a charm, what do you guys think?现在就像一个魅力,你们怎么看? is there a better way to do it?有没有更好的方法来做到这一点? Im kinda new with Django我对 Django 有点陌生

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM