
Django Template Filters to Add HTTPS and Highlight URLs You may use these Django template filters to add HTTPS to your URLs and highlight them as anchor tags (a) with simple code. I have added comments to describe how the code works.
# app/templatetags/app_filters.py
from urlextract import URLExtract
import requests
...
@register.filter(name='addhttpstodomains') # The first filter, to add HTTPS
def addhttpstodomains(value):
domains = re.findall(r'', value) # Regex to get a URL
dic = {}
output = ""
for domain in domains:
if not domain[1].lower() in escaped_domains:
url = 'https://' + domain[1]
if not url.lower().startswith('uglek.com'):
try:
response = requests.head('https://' + domain[1]) # Get the head
if response.status_code == 200: # If the page exists
dic[domain[1]] = 'https://' + domain[1]
except:
print("URL does not exist")
else:
dic[domain[1]] = 'https://' + domain[1]
replaced_items = []
for i, j in dic.items(): # Replace without replacing twice
if not i in replaced_items:
value = value.replace(i, j)
replaced_items.append(i);
value = str(value)
while value.find('https://') > -1: # Remove any duplicates
value = value.replace('https://','https://')
return value
@register.filter(name='embedlinks')
def embedlinks(value):
output = ""
chunks = value.split("https://") # Split at HTTPS
for x, chunk in enumerate(chunks): # Enumerate over split sections
if x != 0:
chunk = "https://" + chunk # Add HTTPS back in
urls = extractor.find_urls(chunk); # Find URL in chunk
dic = {}
for url in urls:
plus = ' (it\'s on Uglek)' # Configure anchor tag
if not url[8:17].lower() == 'uglek.com':
plus = ' (it will take you outside of Uglek)'
if url.endswith('.') or url.endswith(','):
url = url[:-1]
if not url.lower().startswith('uglek.com') and url.lower().startswith('https://'):
try:
response = requests.head(url) # Get the page
if response.status_code == 200: # If it exists
dic[url] = '' + url[8:] + '' # Build anchor tag to replace URL with
except:
print("URL does not exist")
elif url.startswith('https://'):
dic[url] = '' + url[8:] + ''
for i, j in dic.items(): # Find and replace in chunk
chunk = chunk.replace(i, j)
output = output + chunk # Put the pieces back together
return output
{{ post.content|addhttpstodomains|embedlinks }} # Add HTTPS and embed links
Comments (0) Comment
© Uglek, 2022