Reputation: 11784
I'm using django's send_mail to send out an email (using a template) that has the following line in it:
To reset the password, please click the link below:
http://localhost:8000/{% url 'reset_password' uid=uid token=token %}
as you can imagine, this isn't ideal. I have multiple environments (local, staging, dev, prod), each with an entirely different base URL. I want to be able to dynamically generate the domain name, but the url function only provides the path after the root URL (i.e., /reset_password/some_token/).
Is there any way I can dynamically generate the host name? I know I could have an environment variable on each of my machines and put that in my settings.py file, but I'm not the only developer, and our environments may not be able to be updated for a while.
Upvotes: 1
Views: 1483
Reputation: 3831
Beginning with django version 1.5, you are required to define an ALLOWED_HOSTS
setting for authorized access to your website. As this varies by deployment, it can be useful in this case:
from django.conf import settings
# <trimmed> ...
class User(AbstractUser):
# <trimmed> ...
def get_url_notifications(self):
return settings.ALLOWED_HOSTS[0] + reverse('user-notifications')
url_notifications = property(get_url_notifications)
Here, I have added a url_notifications
property to the User
model that returns a full URL to a view in my django site.
And, in settings.py
on each deployment, you have:
# settings.py
# ...
ALLOWED_HOSTS = ['production.example.com', ]
Works great!
Upvotes: 0
Reputation: 2382
You can create a custom template tag for this.
# myapp/templatetags/mytags.py
from django import template
from django.contrib.sites.models import Site
register = template.Library()
@register.simple_tag
def current_domain():
return Site.objects.get_current().domain
Then, In your template, us it like this:
{% load mytags %}
http://{% current_domain %}{% url 'reset_password' uid=uid token=token %}
Upvotes: 1
Reputation: 2882
This is exactly what the sites framework is designed for. The domain name will be stored in the database of the environment and can be edited from the admin interface. You can pass this domain name into the context of your template. For an example:
>>> from django.contrib.sites.models import Site
>>> Site.objects.get_current().domain
"example.com"
Upvotes: 4