Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django build_absolute_uri without query params

Tags:

django

request.build_absolute_uri() returns me url/path/?q1=v1&q2=v2... BUT, I need the same absolute uri without query params q1=v1&q2=v2

like image 841
adrian oviedo Avatar asked Jun 04 '26 13:06

adrian oviedo


2 Answers

The build_absolute_uri method has an optional location. If no location is provided, it uses get_full_path() which includes the querystring. You can pass request.path (which doesn't include the querystring) as the location.

request.build_absolute_uri(request.path)
like image 113
Alasdair Avatar answered Jun 07 '26 16:06

Alasdair


Expanding, if you want to do it from within a template, this is how to do it via writing a simple tag:

  1. In your settings.py, add the following to TEMPLATE['OPTIONS']:
'libraries': {
  'common_extras': 'your_project.templatetags.common_extras',
},
  1. Then, create your_project/templatetags/common_extras.py and add the following:
from django import template

register = template.Library()


@register.simple_tag(takes_context=True)
def clean_url(context):
    request = context['request']
    return request.build_absolute_uri(request.path)
  1. Finally, in your template, you just do:
{% load common_extras %}
...
<meta property="og:url" content="{% clean_url %}">
...
<meta property="twitter:url" content="{% clean_url %}">
like image 38
Carlos Souza Avatar answered Jun 07 '26 17:06

Carlos Souza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!