Created
March 6, 2018 15:43
-
-
Save LowerDeez/6302d26c581bd26c9a387afae96b403f to your computer and use it in GitHub Desktop.
Django. Custom middleware for objects subdomains
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.urlresolvers import reverse | |
from django.shortcuts import get_object_or_404, redirect | |
from .models import Course | |
class SubdomainCourseMiddleware(object): | |
""" | |
Provides subdomains for courses | |
""" | |
def process_request(self, request): | |
host_parts = request.get_host().split('.') | |
if len(host_parts) > 2 and host_parts[0] != 'www': | |
# get course for the given subdomain | |
course = get_object_or_404(Course, slug=host_parts[0]) | |
course_url = reverse('course_detail', | |
args=[course.slug]) | |
# redirect current request to the course_detail view | |
url = '{}://{}{}'.format(request.scheme, | |
'.'.join(host_parts[1:]), | |
course_url) | |
return redirect(url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment