I have applied a template filter, which extracts the domain from an email address. In the template file I have this code:
{% for email in user_list %}
<p>
{{email.email}} corresponds to this domain:
<b> {{email.email|domain}} </b>
</p>
{% endfor %}
It is currently making bold all domain names. What I want to do is to make bold ONLY those email addresses with a 'valid' email extension (for example, only those at the domain '@gmail.com'). How do I apply an if or ifequal statement to do this?
For example, this is the logic I want it to have --
{% for email in user_list %}
<p>
{{email.email}} corresponds to this domain:
{% if domain = 'specified extension' %}
<b> {{email.email|domain}} </b>
{% else %}
{{ email.email|domain }}
{% endif %}
</p>
{% endfor %}
Update:
OK -- I got this working by creating a custom model in models.py
, like so --
class Table(models.Model):
name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
def valid_email(self):
verified = ['yahoo.com','gmail.com']
domain = self.email.split('@')[1]
return domain in verified
And in the template index.html
--
{% for email in user_list %}
<p>
{{email.email}} corresponds to this domain:
{% if email.valid_email %}
<b>{{ email.email|domain}}</b>
{% else %}
{{ email.email|domain}}
{% endif %}
</p>
{% endfor %}
This works well now, but my concern is that when I need to update the models.py
and tamper with the verified email list. Where would be a better place to hold this valid_emails()
function, such that I can update it easily? And then how would I reference the function in the template (if different than current)? Thank you.
You can use the with
template tag to assign email.email|domain
to domain
.
<p>
{{ email.email }} corresponds to this domain:
{% with domain=email.email|domain %}
{% if domain = 'specified extension' %}
<b>{{ domain }}</b>
{% else %}
{{ domain }}
{% endif %}
{% endwith %}
</p>
Note that I've used the Django 1.3 with
syntax. See the docs for earlier versions of Django.
To follow up on Ben James' comment, if you set a list of specified_extensions in the view, you can use in
operator in your if
statement.
In the view:
specified_extensions = ['gmail.com', 'hotmail.com',]
In the template:
{% if domain in specified_extensions %}
...
I think that you have put the valid_emails
method in the correct place, it belongs on the model. If you want to be able to update the list of domains without restarting the server, I suggest you store the domains in the database.
class VerifiedDomain(models.Model):
name = models.CharField(max_length=50, help_text="an allowed domain name for emails, e.g 'gmail.com'")
class Table(models.Model):
name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
def valid_email(self):
domain = self.email.split('@')[1]
return VerifiedDomain.objects.filter(name=domain).exists()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With