0

My urls is not matching with the hashtags. it says 404 url not found. this is my base.html with hashtag:

 $(document).ready(function() {
      $("p").each(function(data) {
        var strText = $(this).html();
        console.log('1. strText=', strText);
        var arrElems = strText.match(/#[a-zA-Z0-9]+/g);
        console.log('arrElems=', arrElems);
        $.each(arrElems, function(index, value){
          strText = strText.toString().replace(value, '<a href="/tags/'+value+'">'+value+'</a>');
        });
        console.log('2. strText=', strText);
        $(this).html(strText);
      });
    });

my hshtag models.py:

from django.db import models
from blog.models import post

# Create your models here.
class HashTag(models.Model):
    tag = models.CharField(max_length=120)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.tag

    def get_postss(self):
        return post.objects.filter(content__icontains="#" + self.tag)

this is my hashtag view:

from django.shortcuts import render
from django.views import View
from .models import HashTag
# Create your views here.


class HashTagView(View):
    def get(self, request, hashtag, *args, **kwargs):
        obj, created = HashTag.objects.get_or_create(tag=hashtag)
        return render(request, 'hashtags/tag_view.html', {"obj": obj})

i put the url intothe primary url of my site:

from hashtags.views import HashTagView
from django.urls import path, re_path, include

urlpatterns = [

re_path(r'^tags/(?P<hashtag>.*)/$', HashTagView.as_view(), name='hashtag'),

]
Jack Ryan
  • 17
  • 10

1 Answers1

0

There is one issue with your implementation. 1. Browser does not send # part to the server. So if your URL is like /tags/#tag then #tag won't be sent to the server. Further read: Why is the hash part of the URL not available on the server side?

Because of this behavior, your browser will hit /tags/ url. That is the reason of your 404 error.

You can check the example of twitter, If the hashtag is #DelhiElectionResults, then the url for that hashtag is https://twitter.com/hashtag/DelhiElectionResults.

Solution: Just remove # from the url and make it like: /tags/tag/. In your JS, you can use value.replace('#', '') to remove the # from the value.

$.each(arrElems, function(index, value){
    strText = strText.toString().replace(value, '<a href="/tags/'+value.replace('#', '')+'">'+value+'</a>');
    });
Nalin Dobhal
  • 2,292
  • 2
  • 10
  • 20