Absolute URL in Django template
I'm just started using Django so my quetion might be stupid :)
I have an URL to a different site in my model(TextField, "othersite.com"). I'm trying to display it in the template like that <a href="{{ article.url }}" >
But tricky Django gives me <a href="http://mysite.com/articles/othersite.com" >
- What do I do to get
开发者_运维知识库<a href="othersite.com" >
? - Sorry for my language, if it has any mistakes :)
Your browser is entering the additional text, instead of Django. This happens in the absence of a complete URL to avoid unexpected behavior.
You can work around the issue by fixing your data, or by modifying your template like this:
<a href="http://{{ article.url }}" >
If all urls need to be absolute, this could be resolved by using a custom template tag and filter.
@register.filter
@stringfilter
def absoluteurl(url):
if "http" not in url:
return 'http://%s' % url
else:
return url
Then you can simply <a href="{{ article.url|absoluteurl }}" >
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
精彩评论