I got a simple def with something like this
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"
Which makes sense since Im calling another function Is there a way to prevent the url from changing?
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.