24
You can use some custom middleware to intercept the request and get the subdomain from it. The following code will retrieve the subdomain and redirect to a view by reversing the named url.
Put it in a middleware.py file in your app.
Make sure you set up the middleware in your settings.py file.
Make sure you’ve named your view in urls.py
middleware.py
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import re
subdomain_pattern = re.compile('(?P<subdomain>.*?)\..*?')
class SubdomainMiddleware(object):
def process_request(self, request):
match = subdomain_pattern.match(request.get_host())
subdomain = match.group('subdomain')
redirect_url = reverse('groups_detail', args=[subdomain])
return HttpResponseRedirect(redirect_url)
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^groups/(?P<name>.+)/$', 'groups.views.detail', {}, name='group_detail'),
)
Note: this code is untested.
Redirecting can alter the URL’s appearance. If you want to avoid this, simply call the associated view, capture its result, and return it in an HttpResponse()
.
2
You need to handle this via your webserver. If you have Django urls like…
/users/<username>/
… then use rewrite rules in the webserver to map <username>.domain.com
to domain.com/users/<username>/
.
If you’re using Apache, you can read up here. Otherwise, each webserver has their own conventions but all will support the notion of url rewrites.
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Django Test Client Method Override Header
- [Django]-Open the file in universal-newline mode using the CSV Django module