Skip to content Skip to sidebar Skip to footer

How Can Make Hashtag Clickable And Show It In The Post In Django?

User can make hashtag. Now I want to make hashtag clickable. Bellow is my Models.py for Hashtag: class Hashtag(models.Model): hashtagname = models.CharField(max_length=3000

Solution 1:

Have you tried using a hyperlink?

{% for readposts in readposts %}
<p class="card-text"> <a href='/putyourlinkhere?hashtag= 
{{readposts.content|linebreaks}}'>{{readposts.content|linebreaks}}</a></p>
{% endfor %}

In views.py:

myhashtag = request.GET.get('hashtag') 

request.GET.get gets the 'hashtag' variable from the link and and saves it to myhashtag variable.

then you can perform a query to search for myhashtag and return the info.


Solution 2:

Try to use this :-

views.py

put this in your working view :-

query = request.GET.gel('q')   
object_list = PostUser.objects.filter(hashtag__hashtagname__icontains=query)

context = {'object_list ':object_list}

template

template where you've done all your view work

{% for tags in object_list %}


{{ tags }}

{{ tags.hashtagname }}

{% endfor %}

Note :- This is not clickable. I want you to try this First.


Solution 3:

I made app_extras.py and init.py in a folder name templatetags in my django app then in the app_extras.py wrote the code bellow and worked

import re
from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe

register = template.Library()

def create_hashtag_link(tag):
    url = "/tags/{}/".format(tag)
    # or: url = reverse("hashtag", args=(tag,))
    return '<a href="{}">#{}</a>'.format(url, tag)


@register.filter(name='hashchange')
def hashtag_links(value):
    return mark_safe(
        re.sub(r"#(\w+)", lambda m: create_hashtag_link(m.group(1)),
               escape(value)))

then in HTML I have loaded the app_extras.py

{% load app_extras %}

Then in my loop html I called the function

{% for readposts in readposts %}
<p class="card-text">{{readposts.content|hashchange|linebreaks}}</p>
{% endfor %}

and also my urls.py I have added

url(r'^tags/(?P<tags>\w+)/$', views.tags, name='tags'),

then of course a view for tag which in this case my view is

def tags(request, tags):
      readpostsuser   = PostUser.objects.filter(content__icontains = tags).order_by('-pk')

return render(request, 'front/tags.html', {'readpostsuser':readpostsuser})

Post a Comment for "How Can Make Hashtag Clickable And Show It In The Post In Django?"