Last active
September 16, 2023 13:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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