wobbily_col
wobbily_col

Reputation: 11931

Reversing urls in Django / Celery

I have been asked to send an email on friday with a list of projects matching a set of conditions. The database front end is written in Django and its an in house application. I would like to link to the admin page of the project in the email.

On my development machine I am trying

reverse("admin:index") 

and I notice that it is only returning

admin 

from the Celery task, whereas in standard Django views this would return

127.0.0.1:8000/admin/

Is there a way around this? I would prefer not to hard code the start of the urls.

I have set up Celery as described in the "first steps with Django" tutorial, and have a

myproject/myproject/celery.py

file defining the app (alongside settings.py and urls.py) and

project/myapp/tasks.py 

file with the actual tasks.

Upvotes: 1

Views: 1239

Answers (2)

knbk
knbk

Reputation: 53699

reverse() always returns a domain-relative url, i.e. /admin/. One option to increase portability is to use the sites framework.

As you don't have a request object in your Celery task, you have to explicitly set the SITE_ID in your settings and set the site's name and domain in your database. Then you can do:

from django.contrib.sites.models import Site
url = "%s%s" % (Site.objects.get_current().domain, reverse('admin:index'))

Upvotes: 1

related
related

Reputation: 840

Usually URLs in django are relative - i.e. the "127.0.0.1:8000" part you see when you hover the link comes from the fact that you are browsing the site from that location. Try looking at the href value of the URLs generated.

A simple solution to your problem is to concatenate the reverse output with the domain, i.e.

'http://example.com/'+reverse('admin:index')

Upvotes: 0

Related Questions