[Django]-Django build_absolute_uri without query params

11👍

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)

0👍

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 %}">

0👍

If you want to get the entire absolute url but without your params there are other properties on the request object you can use and combine them (scheme, get_host and path). It can be used in a template as such:

{{ request.scheme }}://{{ request.get_host }}{{ request.path }}
👤radtek

Leave a comment