簡體   English   中英

在 Django 中加載具有不同數據的相同模板時如何防止 url 更改

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

我得到了一個簡單的 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/date-filter”這樣的東西

這是有道理的,因為我正在調用另一個函數 有沒有辦法防止 url 改變?

大聲笑,寫這個問題我剛剛發現我可以在視圖中調用相同的函數,但是使用 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 有點陌生

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM