Home > Mobile >  How to modify url in a django get request
How to modify url in a django get request

Time:04-27

I have a web page which displays some data (with get parameters to filter in the view) and I use a pagination.

To go through the data i use a link to change the page in the paginator :

<li ><a href="{{ request.get_full_path }}?page={{ page_obj.next_page_number }}">Next</a></li>

Here is the view :

@login_required
def search_and_export(request):

    # initialisation
    page_obj = Tree.objects.all()
    
    # FORM
    if request.method == 'GET':
        
        ## Here I get GET parameters or a default value like 
        
        data = str(request.GET.get('data', 1))
        page = str(request.GET.get('page', 1))
        

        ## creating a queryDict

        querydict = QueryDict('data='  data   '&page='   page)
        big_request_form    = BigRequestForm(querydict)
        
        if big_request_form.is_valid():
            
            # Getting data from front endda
            data    = big_request_form.cleaned_data['data']
            # Extracting QuerySet
            page_obj    = filtering_function(data)

        
        paginator   = Paginator(page_obj,25)

        
        page_obj = paginator.get_page(page)
        page_obj.adjusted_elided_pages = paginator.get_elided_page_range(number = page, on_each_side=1, on_ends=1)

    else:
        big_request_form = BigRequestForm()
    
    # return values

    context = {
        'big_request_form'      : big_request_form,
        'page_obj'              : page_obj,
    }
    
    return render(request, 'filtered_stats.html', context)

Here is the problem : url looks like that after browsing a few pages :

http://127.0.0.1:8000/?data=x&page=2&page=3&page=4&page=5&page=6

The view is working well (It displays me the last page) but I got this ugly link.

I tried something like that :

request.GET.get = querydict

(with querydict a QueryDict object with only one page data) But It didn't work. I also thought of parsing data in the template but maybe there is a better way.

CodePudding user response:

What you want to do in HTML template is to get current URL. But actually you don't have to do it - relative path can be used instead. So just remove it:

<li ><a href="?page={{ page_obj.next_page_number }}">Next</a></li>

The browser knows current URL and will use href attribute relative to it.

UPD alternative - to keep other parameters in the URL is to construct "next URL" inside the view and pass it in context as next_url.

I.e. something like so:

In views:

 next_url = request.get_full_path()
 next_url.replace(f'page={current}', f'page={page_obj.next_page_number}')
 context['next_url'] = next_url

In template:

<li ><a href="{{ next_url }}">Next</a></li>
  • Related