Charanjit Kaur
Charanjit Kaur

Reputation: 81

Django - How to pass multiple parameters to URL

I have created a Listings Page where all listings can be searched. From there, a user can click on any particular listing to see further detail. When I go to individual listing page, I am displaying Breadcrumb to provide an option to go back to Search results (which was previous Listings page).

The issue is I am not able to pass 2 parameters (one containing the previous URL so that I can use that for Breadcrumb back to search results) while calling individual listing page from listings page. Please see main code:

views.py

def listing(request, listing_id, query):
  listing = get_object_or_404(Listing, pk=listing_id)
  

  context = {
    'listing': listing,
    'query':query
  }

  return render(request, 'listings/listing.html', context)

HTML template

{% url 'listing' listing_id=listing.id path=12 %}

I tried using {{ request.get_full_path }} to find path and then add to parameter but its not working. Any suggestions on how to capture URL will be appreciated.

Upvotes: 7

Views: 28230

Answers (3)

Sanket Patil
Sanket Patil

Reputation: 1095

request.GET.getlist("get_full_path []", [])

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

You can work with:

{% url 'listing' listing_id=listing.id path=request.get_full_path %}

but then the path will have to accept this. So it will look like:

path('foo/<int:listing_id>/<path:path>/', …)

It also looks quite chaotic, especially since it will percentage-escape all sorts of question marks and ampersands.

Probably a slighly cleaner solution is to encode this in the querystring, so then it looks like:

path('foo/<int:listing_id>/', …)

the view looks like:

def listing(request, listing_id):
  listing = get_object_or_404(Listing, pk=listing_id)
  

  context = {
    'listing': listing,
    'query': request.GET.get('query')
  }

  return render(request, 'listings/listing.html', context)

and we render the link with to the listing with:

{% url 'listing' listing_id=listing.id %}?query={{ request.get_full_path|urlencode }}

But it simply does not look very pleasant to encode the entire path in the URL. If you have a search page, you can perhaps simply encode the search query itself (so not the path, but the content the person has written in the search bar). This makes the URL shorter, and more visually pleasant.

Upvotes: 4

SLDem
SLDem

Reputation: 2182

Try this in your urls.py:

urlpatterns = [
    path('listing/<int:pk>/<int:path>/', views.listing, name='listing')
]

Upvotes: 3

Related Questions