Skip to content

Instantly share code, notes, and snippets.

@foxy4096
Last active September 16, 2023 13:18
Show Gist options
  • Select an option

  • Save foxy4096/9349961dc7ac350e4914a531a056ff11 to your computer and use it in GitHub Desktop.

Select an option

Save foxy4096/9349961dc7ac350e4914a531a056ff11 to your computer and use it in GitHub Desktop.
A template tag to convert @username to a link also God please help me with this abomination
from django import template
from django.template.defaultfilters import stringfilter
from django.contrib.auth.models import User
from django.urls import reverse_lazy
register = template.Library()
@register.filter(name='mention', is_safe=True)
@stringfilter
def mention(value):
my_list = value.split()
for i in my_list:
if i[0] == '@':
try:
stng = i[1:].replace(',', '').replace('.', '').replace('!', '').replace('?', '').replace(';', '').replace(':', '').replace('-', '').replace('_', '').replace('(', '').replace(')', '').replace('[', '').replace(']', '').replace('{', '').replace('}', '').replace(
'/', '').replace('\\', '').replace('*', '').replace('+', '').replace('=', '').replace('%', '').replace('$', '').replace('#', '').replace('^', '').replace('&', '').replace('|', '').replace('~', '').replace('`', '').replace('<', '').replace('>', '')
user = User.objects.get(username=stng)
if user:
profile_link = reverse_lazy('profile_view', kwargs={
'username': user.username})
j = f"<a href='{profile_link}'>{i}</a>"
value = value.replace(i, j)
except User.DoesNotExist:
print("Could not get the data")
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment