Reversing urls in Django / Celery - django

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.

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'))

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')

Related

django project derived from python-socketio django example unable to server other URLs (at least in django 1.11)

After playing with python-socketios django_example, and seeing that it worked great, I created a new django project, configured it just like the example, copied over the example app to the project (complete with it's overriding of the runserver management command). Everything worked fine, and I was able to make my a few changes so that you can set a nick, some redis stuff to lookup up the sid for a nick, and was able to support sending private messages to a nick. Everything was still working great.
I figured the next logical step was to, rather than having to manually set a nick, require the user to login, expose their username as a var in a script block in the template (I moved scripts/index.html to templates/index.html), and automatically have the javascript emit my custom 'set_nick' event with the username automatically upon connect.
I defined LOGIN_URL = '/accounts/login' in settings.py, included 'django.contrib.auth.urls' in my urls.py and wrapped the index view with #login_required.
It was only then that I noticed that no matter what URL you request, you always get the chat apps index view - no login page redirect, '/admin/' is ignored, etc.
EDIT Solved - See my answer below.
I noticed that the urls.py which I blindly copied over from the example looked like this:
url(r'', include('socketio_app.urls')),
url(r'^admin/', admin.site.urls),
and the r'' was the culprit (matches everthing). Changing this to:
url(r'^/', include('socketio_app.urls)),
url(r'^admin/', admin.site.urls),
However, I'm using Django==1.11. I believe Django 2 tends to suggest using path (or some similarly named function) rather than using url. I don't believe, however, that the semantics of url are different in Django 2, so this is probably an issue for Django 2 users as well.

Integrating Sphinx and Django in order to require users to log in to see the documentation

I am curious if it is possible to hide sphinx documentation inside a django app so that only people who log in can see it. It seems to me that since sphinx creates its own structure and that Django uses the urlconf to define which pages a user can see, that it wouldn't be possible to combine the two. Although there must be some combining since the Django website likely uses django and sphinx. I am wondering if anyone has any insight or if they can point me in the right direction.
Thank You in Advance!
Sphinx builds your docs into HTML files, so in most cases this docs should be served by your web server rather then Django. However Django is able to serve static files as well.
You can use the django.views.static.serve function to do this and wrap this function with login_required. E.g:
from django.views.static import serve
from django.contrib.auth.decorators import login_required
urlpatterns += patterns('',
url(r'^docs/(?P<path>.*)', login_required(serve), {'document_root': '/path/to/sphinx/build/html'}, 'docs'),
)
However this configuration will be considered a bad practice in production environment as in this case Django will serve both html and css/js files from your sphinx theme.
The first improvement you can do here is to serve /path/to/sphinx/build/html/_static/ with apache/nginx or whatever you use.
The more proper way is to serve docs with apache/nginx and make it handle the auth itself. Unfortunately I made a quick Google search but did not find a way to use Django's User model to handle http_auth in apache or other. Alternatively you can use something like mod_sendfile or X-Accel modules - http://www.wellfireinteractive.com/blog/nginx-django-x-accel-redirects/ In a nutshell - Django app checks permission if user can view the file and add special header to response containing file path. Webserver will serve this file instead of original message from django

Hosting Django Project at /test #login_required redirects to /accounts instead of /test/accounts

I'm moving a project to new hosting and would like to set it up such that it sits at mysite.com/test/ (this is under mod_wsgi on an Apache server). This seems to do alright for the application itself, but when I use #login_required to enforce authentication Django redirects to mysite.com/accounts/login instead of mysite.com/test/accounts/login as I would like. I also have a mysite.com/prod that I want to do this same thing on so I don't want to hard code this anywhere in settings... it should figure out where the root of its URL is and act accordingly.
How do I set it up so that Django automagically redirects to what Apache considers that application's web root?
You need to set LOGIN_URL and LOGOUT_URL to full URL path in Django settings file. See:
http://docs.djangoproject.com/en/1.3/ref/settings/#login-url
Django doesn't automatically insert the mount point at the start of those as so have to be fully qualified.
The same problem can be solved in a more generic way for all project URLs. You could checkout an alternative solution at Running a Django site on my local machine, am I redirecting my URLs properly? for an environment based ROOT URL support.

Apache | Django: How to run websites on the back of a base URL?

I've got a base url. http://baseurl.com/
I'm trying to run projects on the back of it. For example
http://baseurl.com/mongoose/
The projects run but the URL don't work properly because they all
reference the base url. So for 'About Me' page it points to
http://baseurl.com/about instead of http://baseurl.com/mongoose/about
Is this something i need to change in django or apache? Is what I'm
trying to do even possible?
Coming from an IIS .net background I know that in IIS you can "Create and application" within a site which essentially does what I'm trying to achieve now with Apache and Django.
Thanks
You shouldn't need to do anything. Apache is supposed to be setting a request header called SCRIPT_NAME, which is your base URL, and all URL reversing takes that into account.
How are you creating these URLs in your templates?
Update
So your problem is with getting the URLs of Flatpages. The issue is that the normal way of calculating URLs dynamically, so that they do take SCRIPT_NAME into account - using the reverse() function or the {% url %} tag - doesn't work with Flatpages, because they are not dispatched via urls.py but via a custom middleware which fires on a 404.
So instead of using that middleware, I would use the urls.py mechanism to dispatch to flatpages. Remove the flatpagemiddleware from your settings.py, and in urls.py at the end of your patterns add this:
url(r'^(?P<url>.*)$', 'django.contrib.flatpages.views.flatpage', name='flatpage'),
Now, in your templates, you can do:
<a href="{% url flatpage page.url %}">
and it should work correctly.
Check any urls.py in the project(s) to see if they expect to be top-level. But if the application outputs links like /something then it's going to mean the root directory. The application should be reversing a view/parameter into a URL, which would allow you to move it around. If you wrote the apps, check out reverse in django.core.urlresolvers

How to make Django url dispatcher use subdomain?

I have a vague idea on how to solve this, but really need a push :)
I have a Django app running with apache (mod_wsgi). Today urls look like this:
http://site.com/category/A/product/B/
What I would like to do is this:
http://A.site.com/product/B
This means that the url dispatcher some how needs to pick up the value found in the subdomain and understand the context of this instead of only looking at the path. I see two approaches:
Use .htaccess and rewrites so that a.site.com is a rewrite. Not sure if this does the trick since I don't fully understand what the django url dispatcher framework will see in that case?
Understanding how the url dispatcher DO work I could write a filter that looks at valid sub domains and provides this in a rewritten format to the url dispatcher code.
Any hints or solutions are very much appreciated! Thanks.
Have you looked at django.contrib.sites? I think a combination of that, setting SITE_ID in your settings.py, and having one WSGI file per "site" can take care of things.
EDIT: -v set.
django.contrib.sites is meant to let you run multiple sites from the same Django project and database. It adds a table (django.contrib.sites.models.Site) that has domain and name fields. From what I can tell, the name can mean whatever you want it to, but it's usually the English name for the site. The domain is what should show up in the host part of the URL.
SITE_ID is set in settings.py to the id of the site being served. In the initial settings.py file, it is set to 1 (with no comments). You can replace this with whatever code you need to set it to the right value.
The obvious thing to do would be to check an environment variable, and look up that in the name or domain field in the Site table, but I'm not sure that will work from within the settings.py file, since that file sets up the database connection parameters (circular dependency?). So you'll probably have to settle for something like:
SITE_ID = int(os.environ.get('SITE_ID', 1)
Then in your WSGI file, you do something like:
os.environ['SITE_ID'] = 2
and set that last number to the appropriate value. You'll need one WSGI file per site, or maybe there's a way to set SITE_ID from within the Apache setup. Which path to choose depends on the site setup in question.
The sites framework is most powerful where you use Site as the target of a ForeignKey or ManyToManyField so that you can link your model instances (i.e. records) to specific sites.
Mikes solution is correct if you want to have multiple sites with same apps with different content (sites module) on multiple domains or subdomains, but it has a drawback that you need to be running multiple instances of the Django process.
A better solution for the main problem about multiple domains or subdomains is to use a simple middleware that handles incoming requests with the process_request() function and changing the documented urlconf attribute (link) of the request object to the URLconf you want to use.
More details and an example of the per-request or per-domain URL dispatcher can be found at:
http://gw.tnode.com/0483-Django/
Try adding a wildcard subdomain: usually *.