Javascript 在django中,hashtag和URL不匹配
我的URL与哈希标记不匹配。它说找不到404URL。 这是带有hashtag的my base.html:Javascript 在django中,hashtag和URL不匹配,javascript,django,hashtag,Javascript,Django,Hashtag,我的URL与哈希标记不匹配。它说找不到404URL。 这是带有hashtag的my base.html: $(document).ready(function() { $("p").each(function(data) { var strText = $(this).html(); console.log('1. strText=', strText); var arrElems = strText.match(/#[a-zA-Z0
$(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);
});
});
这是我的标签视图:
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})
我将url放入我网站的主url中:
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'),
]
从hashtags.views导入HashTagView
从django.url导入路径,re_路径,包括
URL模式=[
re_path(r'^tags/(?P.*)/$),HashTagView.as_view(),name='hashtag'),
]
您的实现存在一个问题。
1.浏览器不会将#零件发送到服务器。因此,如果您的URL类似于/tags/#tag
,那么#tag
将不会被发送到服务器。进一步案文:
由于这种行为,您的浏览器将点击/tags/
url。这就是您的404错误的原因
您可以查看twitter的示例,如果标签是#DelhiElectionResults,则该标签的url是https://twitter.com/hashtag/DelhiElectionResults
解决方案:只需从url中删除#
,并将其设置为:/tags/tag/
。在JS中,可以使用value.replace('#','')
从值中删除
$。每个(参数、函数(索引、值){
strText=strText.toString().replace(值“”);
});
你的意思是从我的URL.py中删除“#”吗@纳林多巴尔
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'),
]