简体   繁体   中英

Django: using python methods

I'm trying to truncate my urls that are being populated into html table like so:

{% for x in queryset %}
<tr> 
<td>{{x.LINK}}</td>
</tr>

so that ie 'www.google.com' becomes 'google'. How to achieve it? In python it would be straight forward with .split('.') method but here I'm confused. Or maybe it would be simplier to do all the data modifications before I query them in django?

EDIT: Just noticed your example contains a simplified but malformed URL. This simpler template tag will work for URLs formatted like 'www.google.com':

@register.simple_tag()
def get_domain_name_from_url(url):
    return url.split('.')[-2]

If you're dead-set on doing this in the template, you can make a custom template tag :

As long as your URLs are properly formatted (eg "https://www.google.com/"), this should do the trick:

from django import template
register = template.Library()

from urllib.parse import urlparse

@register.simple_tag()
def get_domain_name_from_url(url):
    parsed_url = urlparse(url)
    netloc = parsed_url[1]
    domain_name = netloc.split('.')[-2]
    return domain_name

How it works:

  1. urlparse parses the domain into a 6-item named tuple.
  2. The second tuple item ( parsed_url[1] ) is a string containing the network location part of the URL (eg "www.google.com" )
  3. Split the string into its component parts using split('.') , and return the second-last item in the list ( "google" ). By getting the part before the TLD ( .com ), we avoid any issues that arise if we work from the beginning. (eg if the URL does not contain www , we will want the first item in the list, not the second. By starting with the TLD and working backwords, we should always get the domain name.)

Save the code in a file named [your_django_project]/[your_app]/templatetags/get_domain_name.py .

Make sure the app is in your INSTALLED_APPS in settings.py .

Restart the server. (Don't forget this part. The server registers your template tags when it starts.)

Now, in your template, you can load the code:

{% load get_domain_name %}
{% get_domain_name_from_url x.LINK %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM