'How to add query parameters to the <a href=

I want to redirect from one page to another (and save the query parameters). So i redirect like

base.html
<tr>
<td> <a href="search/"></a></td>
<td>...</td>
</tr>
urls.py
 path('main/search/', views.x, name='table_query')
views.py
@login_required
@inject_session_params
def table_structure(request, user_data, *args, **kwargs):
    if request.method=='GET':
        user_data['table']=kwargs['table']
        user_data['structure'] = getTableProps(kwargs['table'])
    else:
        return redirect('login')
    return render(request, 'x.html', user_data)

I have got al the needed information which I would like to use for the query, but I am not sure how to use it inside <a>.

I have tried to create another function, which would generate the url and then redirect to the needed view, but it gives me an error. This is what I have tried:

base_url=reverse('table_query')
query = urlencode({'x': x, 'y': y, 'z': z})
url='{}?{}'.format(base_url,query)

How to add query parameters (with a function) inside a tag, without writing <a href="search?x=x&y=y&z=z"?



Solution 1:[1]

In the end this is how I have solved the question:

<a href="{% url 'abc' %}?x={{ x}}&y={{ y}}&z={{ z}}"></a>

Solution 2:[2]

You can add it in the response context:

# views.py
@login_required
@inject_session_params
def table_structure(request, user_data, *args, **kwargs):
    if request.method=='GET':
        user_data['table']=kwargs['table']
        user_data['structure'] = getTableProps(kwargs['table'])
        user_data['query'] = urlencode({'x': x, 'y': y, 'z': z})
    else:
        return redirect('login')
    return render(request, 'x.html', user_data)

and then in template x.html:

<tr><td> 
<a href="{% url 'table_query' %}?{{ query }}"></a>

</td></tr>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eli
Solution 2 DanielM