开发者

Variables in Django

I am trying to create a basic template which displays the emails and corresponding domains from a CSV file.

My emails.html file is:

<html>
<head>Emails</head>
<body>
    <ul>
        {% for email in email_list %}
        <li> {{email}} </li>
        <li> {{domain}} </li>
        {% endfor %}
    </ul>
</body>

And my views.py file is:

def emails(request):
    f = open('/Users/name/Desktop/emails.csv')
    em开发者_JAVA技巧ail_list = f.read().split()
    # domain = email.split('@')[1]
    return render_to_response('emails.html', {'email_list':email_list, 'domain':domain})

What is the correct way to reference the 'email' variable contained in the html file? For example, if I was doing the function in one script, I would have it as:

for emails in 'list of emails':
    domain = emails.split('@')[1]
    print emails, domain

What is the correct expression to use in views.py to express this? Thank you.


Create a custom filter as described here

E.g.,:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(name='domain')
@stringfilter
def domain(value):
    if '@' in value:
        return value.split('@')[1]

Usage (assuming the templatetags module you're using is called email_tags.py):

{% load email_tags %}
<html>
<head>Emails</head>
<body>
    <ul>
        {% for email in email_list %}
        <li> {{email}} </li>
        <li> {{email|domain}} </li>
        {% endfor %}
    </ul>
</body>

You would create a templatetags directory in your app (and make sure to add a __init__.py file so it's a module).

This may seem overkill, but it's a very useful way to add power to Django templates.


You could also do the domain parsing in the view if you don't like template tags (I don't like template tags)

def emails(request):
  f = open('/Users/name/Desktop/emails.csv')
  email_list = f.read().split()
  email_domain_set = []  # a list of dictionaries
  for email in email_list:
    #guard against data integrity problems (i.e. email doesn't have an @)
    try:
      email_domain_dict = {"email":email, "domain": email.split('@')[1]}
      email_domain_set.append(email_domain_dict)        
    except IndexError:
      pass
      # if we want to see errors, but not fail, could do that like this 
      #email_domain_dict = {"email":email, "domain": "ERROR"}
      #email_domain_set.append(email_domain_dict)        

  return render_to_response('emails.html', {'email_domain_set':email_domain_set})

Then in your template

<html>
<head>Emails</head>
<body>
    <ul>
        {% for item in email_domain_set %}
        <li> {{item.email}} </li>
        <li> {{item.domain}} </li>
        {% endfor %}
    </ul>
</body>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜