absolute url in template and url name

2,953 views
Skip to first unread message

robos85

unread,
Nov 24, 2010, 8:01:58 AM11/24/10
to Django users
Hi,
I'm writing an email sending module based on on templates. I have no
idea how to put absolute url to my template (for example
http://domain.com/account/activate/2). I have special url for this,
named account_activation.
I know how to pass variables but how to create that url?
Shouls I use {{ url }} tag? It creates relative paths starting
with / :/

robos85

unread,
Nov 24, 2010, 8:16:11 AM11/24/10
to Django users
small correction not {{ url }} but {% url %} ?

On 24 Lis, 14:01, robos85 <prog...@gmail.com> wrote:
> Hi,
> I'm writing an email sending module based on on templates. I have no
> idea how to put absolute url to my template (for examplehttp://domain.com/account/activate/2). I have special url for this,

Jason Mayfield

unread,
Nov 24, 2010, 8:34:41 AM11/24/10
to django...@googlegroups.com
Pass the current Site object into the template as part of the context. Then you can do: {{ current_site.domain }}{% url account_activation %} for the absolute url.

> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>

- Jason

robos85

unread,
Nov 24, 2010, 9:08:38 AM11/24/10
to Django users
I managed to render it properly:
html_template = loader.get_template('emails/confirm_account.html')
email_vars = Context({'registration_hash' : '123456',
'new_email' : 'ma...@mail.com'})

What do You mean "current Site object"?

Jason Mayfield

unread,
Nov 24, 2010, 9:33:26 AM11/24/10
to django...@googlegroups.com
On Nov 24, 2010, at 9:08 AM, robos85 wrote:

> What do You mean "current Site object"?

from django.contrib.sites.models import Site


current_site = Site.objects.get_current()


email_vars = Context({'registration_hash' : '123456',

'new_email' : 'ma...@mail.com',
'current_site': current_site})


Documented here:

http://docs.djangoproject.com/en/1.2/ref/contrib/sites/#getting-the-current-domain-for-full-urls

- Jason

Jumpfroggy

unread,
Nov 24, 2010, 3:39:04 PM11/24/10
to Django users
I always do something like this:

abs_activate_url =
request.build_absolute_uri(reverse('account_activate', args=user.id))

That's an absolute URL, so it's like "http://domain.com/account/
activate/2" instead of the normal reverse() or {% url %} which gives a
relative URL like "/account/activate/2". Then you can use it just
like others have stated:

from django.template.loader import render_to_string
email_body = render_to_string('email_template.html', {
'abs_activate_url': abs_activate_url,
}

Jason Mayfield's "current site" method seems easier, since you don't
have to make & pass all the absolute URLs first.

ryan west

unread,
Nov 24, 2010, 6:53:41 PM11/24/10
to Django users
if you have a view let's say views.activate that corresponds to the
URL at let's say /account/activate/2, you can use the template tag {%
url views.activate params_for_url_capturing %}

Cheers

On Nov 24, 8:01 am, robos85 <prog...@gmail.com> wrote:
> Hi,
> I'm writing an email sending module based on on templates. I have no
> idea how to put absolute url to my template (for examplehttp://domain.com/account/activate/2). I have special url for this,

Sells, Fred

unread,
Nov 25, 2010, 10:44:48 AM11/25/10
to django...@googlegroups.com
I'm trying to get django to email exceptions to me, now that my app is
in production. I'm testing under Windows7 but will deploy under Linux
CENTOS

The following code works as a test (server names changed to protect the
innocent:
from django.core.mail import EmailMessage
import os
def run():
filenames = os.listdir('.')
filenames = [x for x in filenames if x.endswith('.py')]

subject = "django email test"
message = "this is a test"
email = EmailMessage(subject, message, 'mds30 server',
[m...@mydomain.org'], )
for filename in filenames:
email.attach_file(filename)
email.send()
========================================================================
===================
However I cannot get django to email exceptions to me. But it is
detecting them. Code snippets follow

-----------settings.py
DEBUG = False
TEMPLATE_DEBUG = True #also tried False

ADMINS = (
('Fred Sells', m...@mydomain.org'),
)
EMAIL_HOST = "mail.mydomain.org"
EMAIL_HOST_USER = '' #also tried with my username and password
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = 'frs...@mydomain.org'
SERVER_EMAIL = 'frs...@mydomain.org'
MANAGERS = ADMINS

--------------I've put some print statements in core/handlers.base.py
and it seems ok
print 'aaaaa', subject
try:
request_repr = repr(request)
except:
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (self._get_traceback(exc_info),
request_repr)
print 'bbbbbbbbbb', message
print 'ccccccc', resolver.urlconf_module
mail_admins(subject, message, fail_silently=False)
# If Http500 handler is not installed, re-raise last exception
if resolver.urlconf_module is None:
raise exc_info[1], None, exc_info[2]
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve500()
print 'dddddd', callback, param_dict

which shows...

what you would expect, ending with
ccccccc <module 'mds30.urls' from
'C:\temp\DjangoSouthRecovery\mds30\urls.pyc'>
core.mail None
dddddd <function server_error at 0x031BEA70> {}

--------------------but when I look at core/mail/__init__.py I see
this....
def mail_admins(subject, message, fail_silently=False, connection=None):
"""Sends a message to the admins, as defined by the ADMINS
setting."""
if not settings.ADMINS:
return
print 'core.mail', connection
EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],

connection=connection).send(fail_silently=fail_silently)

----------which prints
core.mail None

looking at the code, I see that base does not pass a connection, but
mail expects one and defaults to None. Obviously others are using this
ok, so I must be missing something. Can someone explain what I'm
missing.

Sells, Fred

unread,
Nov 27, 2010, 9:50:40 AM11/27/10
to django...@googlegroups.com
Please ignore previous, it was working but getting lost in my spam
filter.

Jumpfroggy

unread,
Nov 29, 2010, 11:55:44 AM11/29/10
to Django users
As a followup, I had to do something similar and ended up using this:

# Gets the http://domain.com without the trailing /
base_url = request.build_absolute_uri('/')[:-1]

And in the template I can do this:

<a href="{{ base_url }}{% url some_view_name %}">...</a>

The benefits:
-You only have to create the base_url in the view, the rest you can do
in the template itself.
-The URLs are absolute & contain the domain (ie. http://www.domain.com/page/1,
https://www.domain.com:8008/view2, etc).
-Includes http & https.
-Simple.

This the method I'm using from now on.
Reply all
Reply to author
Forward
0 new messages