### Build Documentation with Make Source: https://github.com/jazzband/django-hosts/blob/master/CONTRIBUTING.md Run this command in the root directory to build the project's documentation. Ensure you have the necessary build tools installed. ```bash make docs ``` -------------------------------- ### Install Django-Hosts Source: https://github.com/jazzband/django-hosts/blob/master/README.rst Install the django-hosts package using pip. This is the first step in integrating the library into your Django project. ```shell pip install django-hosts ``` -------------------------------- ### Define Host Patterns Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Define host patterns for your Django project. This example shows a basic setup with an admin host. ```python from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( "", host(r"admin", settings.ROOT_URLCONF, name="our-admin"), ) ``` -------------------------------- ### Define Root URL Configuration Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Define the URL patterns for your root URL configuration. This example includes a dashboard path. ```python from django.urls import path urlpatterns = [ path("dashboard/", "dashboard", name="dashboard"), ] ``` -------------------------------- ### Define Host Patterns for Multiple Hosts Source: https://github.com/jazzband/django-hosts/blob/master/README.rst This example shows how to route requests for multiple hosts, such as foo.example.com and bar.example.com, to a single URL configuration using a regular expression. ```python from django_hosts import patterns, host host_patterns = patterns( "", host(r"(foo|bar)", "path.to.urls", name="foo-or-bar"), ) ``` -------------------------------- ### Clean Documentation Build Source: https://github.com/jazzband/django-hosts/blob/master/CONTRIBUTING.md Use this command to clean the documentation build directory and remove the temporary virtual environment. This is useful for starting a fresh build. ```bash make clean ``` -------------------------------- ### Reverse Hostname with reverse_host() Source: https://context7.com/jazzband/django-hosts/llms.txt Use reverse_host() to get only the hostname for a named host, useful for custom URL construction. Supports positional and keyword arguments for dynamic hosts. ```python from django_hosts.resolvers import reverse_host, reverse_host_lazy # Basic usage - get the hostname for a named host hostname = reverse_host('www') # Output: 'www.example.com' hostname = reverse_host('api') # Output: 'api.example.com' # With positional arguments for dynamic hosts hostname = reverse_host('wildcard', args=('mysubdomain',)) # Output: 'mysubdomain.example.com' # With keyword arguments for named capture groups hostname = reverse_host('user-sites', kwargs={'username': 'johndoe'}) # Output: 'johndoe.users.example.com' # Lazy version for module-level assignment DEFAULT_HOSTNAME = reverse_host_lazy('www') ``` -------------------------------- ### Pass Parameters to host_url Tag Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Pass parameters to the `host_url` template tag to generate URLs with dynamic host parts or view arguments. This example includes named and positional parameters. ```html+django {% load hosts %} John's dashboard FAQ ``` -------------------------------- ### Append PARENT_HOST to URLs Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Configure `PARENT_HOST` to append a default domain to generated URLs. This example shows the rendered link with the appended domain. ```python PARENT_HOST = "example.com" ``` -------------------------------- ### Override Scheme Individually Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Override the URL scheme on a case-by-case basis using the `scheme` parameter in the `host_url` template tag. This example sets the scheme to 'https'. ```html+django {% load hosts %} John's dashboard FAQ ``` -------------------------------- ### Define API and Beta Host Patterns Source: https://github.com/jazzband/django-hosts/blob/master/README.rst Use this to define host patterns for specific subdomains like api.example.com and beta.example.com, routing them to their respective URL configurations. ```python from django_hosts import patterns, host host_patterns = patterns( "path.to", host(r"api", "api.urls", name="api"), host(r"beta", "beta.urls", name="beta"), ) ``` -------------------------------- ### Define Host Patterns with patterns() and host() Source: https://context7.com/jazzband/django-hosts/llms.txt Use `patterns()` to create a list of host configurations and `host()` to define individual patterns. Each `host()` can specify a regex for matching, a URL configuration, an optional callback, and custom scheme/port settings. Wildcard patterns should come after specific ones. ```python # mysite/hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', # Static host - routes www.example.com to main URLs host(r'www', settings.ROOT_URLCONF, name='www'), # API subdomain with dedicated URL configuration host(r'api', 'mysite.api_urls', name='api'), # Admin with HTTPS-only scheme host(r'admin', 'mysite.admin_urls', name='admin', scheme='https://'), # Wildcard host matching any subdomain (must come after specific patterns) host(r'(\\w+)', 'mysite.custom_urls', name='wildcard'), # Named parameter capture for user subdomains host(r'(?P\\w+)\\Users', 'mysite.user_urls', name='user-sites'), ) ``` ```python # With prefix - automatically prepends 'path.to' to all urlconf paths host_patterns = patterns('path.to', host(r'api', 'api.urls', name='api'), # Becomes 'path.to.api.urls' host(r'beta', 'beta.urls', name='beta'), # Becomes 'path.to.beta.urls' ) ``` ```python # With custom port host_patterns = patterns('', host(r'api', 'api.urls', name='api', scheme='https://', port=8443), ) ``` -------------------------------- ### Rendered Links with Parameters Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md The rendered output of `host_url` when parameters are passed, demonstrating dynamic URL generation with `PARENT_HOST`. ```html+django John's dashboard FAQ ``` -------------------------------- ### Define Dynamic Host Patterns Source: https://github.com/jazzband/django-hosts/blob/master/docs/index.md Use regular expressions in host patterns to create dynamic host schemes. Ensure more specific patterns like 'www' are placed before broader ones like '\w+' to maintain correct routing. ```python from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( "", host(r"www", settings.ROOT_URLCONF, name="www"), host(r"(\w+)", "path.to.custom_urls", name="wildcard"), ) ``` -------------------------------- ### Configure Host Patterns with a Callback Source: https://github.com/jazzband/django-hosts/blob/master/docs/callbacks.md Pass the callback function as a string to the 'callback' parameter when defining a host pattern. This associates the callback with the matching host. ```python from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( "", host(r"www", settings.ROOT_URLCONF, name="www"), host( r"(?P\w+)", "path.to.custom_urls", callback="path.to.custom_fn", name="with-callback", ), ) ``` -------------------------------- ### Define Host Pattern with Domain Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Alternatively, spell out the full domain in the host pattern to avoid using `PARENT_HOST` for all URLs. ```python from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( "", host(r"admin\.example\.com", settings.ROOT_URLCONF, name="admin"), ) ``` -------------------------------- ### Generate Admin Dashboard Link Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Use the `host_url` template tag to create a link to the admin dashboard. Ensure `{% load hosts %}` is included. ```html+django {% load hosts %} Admin dashboard ``` -------------------------------- ### Built-in Site Callbacks for Site Matching Source: https://context7.com/jazzband/django-hosts/llms.txt Utilize built-in callbacks like `host_site` and `cached_host_site` to automatically match incoming hosts to Django's `Site` model instances. ```python # mysite/hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns ('', host(r'www', settings.ROOT_URLCONF, name='www'), # Use host_site callback - matches host to Site model host( r'(?P\w+)', 'mysite.user_urls', callback='django_hosts.callbacks.host_site', name='user-sites', ), # Use cached_host_site for better performance (uses cache backend) host( r'(?P\w+)', 'mysite.tenant_urls', callback='django_hosts.callbacks.cached_host_site', name='tenant-sites', ), ) ``` ```python # settings.py # Configure cache timeout for cached_host_site (default: 3600 seconds) HOST_SITE_TIMEOUT = 7200 # 2 hours ``` ```python # mysite/views.py from django.shortcuts import render def tenant_home(request): """View that uses request.site set by the callback.""" # request.site is a Site instance matching the current host site = request.site # Lazily loaded Site object return render(request, 'tenant_home.html', { 'site_name': site.name, 'site_domain': site.domain, }) ``` -------------------------------- ### Define Host Patterns with Parameters Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Define host patterns that include parameters, such as named capture groups, to be used with the `host_url` tag. ```python from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( "", host(r"www", settings.ROOT_URLCONF, name="homepage"), host(r"(\w+)", "path.to.support_urls", name="wildcard"), host(r"(?P\w+).users", "path.to.user_urls", name="user-area"), ) ``` -------------------------------- ### Configure Django Debug Toolbar Middleware Order Source: https://github.com/jazzband/django-hosts/blob/master/docs/faq.md Ensure Django Debug Toolbar works correctly by placing its middleware after django-hosts' HostsRequestMiddleware. ```python MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", # your other middlewares.. "debug_toolbar.middleware.DebugToolbarMiddleware", "django_hosts.middleware.HostsResponseMiddleware", ] ``` -------------------------------- ### Testing Host Routing with Django Client Source: https://context7.com/jazzband/django-hosts/llms.txt Simulate requests to different hosts during testing by setting the `SERVER_NAME` parameter in `django.test.Client` methods. This is crucial for verifying host-specific routing and behavior. ```python # tests/test_views.py from django.test import TestCase, Client class HostRoutingTests(TestCase): def setUp(self): self.client = Client() def test_www_host(self): """Test request to www subdomain.""" response = self.client.get('/', SERVER_NAME='www.example.com') self.assertEqual(response.status_code, 200) def test_api_host(self): """Test request to api subdomain.""" response = self.client.get('/endpoint/', SERVER_NAME='api.example.com') self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {'status': 'ok'}) def test_post_with_host(self): """POST requests require SERVER_NAME to route correctly.""" response = self.client.post( '/submit/', data={'key': 'value'}, content_type='application/json', SERVER_NAME='api.example.com' ) self.assertEqual(response.status_code, 201) def test_wildcard_host(self): """Test dynamic wildcard subdomain.""" response = self.client.get( '/dashboard/', SERVER_NAME='johndoe.users.example.com' ) self.assertEqual(response.status_code, 200) # Verify callback attached the user self.assertEqual(response.context['viewing_user'].username, 'johndoe') ``` -------------------------------- ### Configure django-hosts Middleware and Settings Source: https://context7.com/jazzband/django-hosts/llms.txt Add django-hosts middleware to your Django settings and configure required settings like ROOT_HOSTCONF and DEFAULT_HOST. The middleware must be placed at the beginning and end of the MIDDLEWARE list. ```python # settings.py INSTALLED_APPS = [ 'django_hosts', # ... other apps ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', # Must be first 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', # Must be last ] # Required settings ROOT_HOSTCONF = 'mysite.hosts' # Path to your hosts configuration module DEFAULT_HOST = 'www' # Name of the default host pattern # Optional settings PARENT_HOST = 'example.com' # Parent domain appended to reversed hosts HOST_SCHEME = '//' # URL scheme (default: '//' for protocol-relative) HOST_PORT = '' # Port to append (default: empty string) HOST_SITE_TIMEOUT = 3600 # Cache timeout for cached_host_site callback ``` -------------------------------- ### Filter Posts by Current Site in Views Source: https://context7.com/jazzband/django-hosts/llms.txt Use the `on_site.by_request()` manager method to filter posts based on the current site determined by the host. This requires the `host_site` callback to be configured. ```python from django.shortcuts import render from .models import BlogPost, Article def home_page(request): """Filter posts by current site from request.""" # by_request() uses request.site set by host_site callback posts = BlogPost.on_site.by_request(request).all() return render(request, 'home.html', {'posts': posts}) ``` ```python from django.shortcuts import render from .models import BlogPost, Article def article_list(request): """Filter articles by a specific site object.""" articles = Article.on_site.by_site(request.site).order_by('-created_at') return render(request, 'articles.html', {'articles': articles}) ``` ```python from django.shortcuts import render from .models import BlogPost, Article def admin_posts_by_site(request, site_id): """Filter by site ID directly.""" posts = BlogPost.on_site.by_id(site_id).all() return render(request, 'admin/posts.html', {'posts': posts}) ``` -------------------------------- ### Rendered Link with PARENT_HOST Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md The rendered link after setting `PARENT_HOST`, showing the appended domain. ```html+django Admin dashboard ``` -------------------------------- ### Generate Full URLs with reverse() and reverse_lazy() Source: https://context7.com/jazzband/django-hosts/llms.txt Use `reverse()` and `reverse_lazy()` from `django_hosts.resolvers` to generate fully qualified URLs. You can specify the view name, host, scheme, port, and arguments (positional or keyword) for URL construction. `reverse_lazy` is useful for class-based views and module-level definitions. ```python from django_hosts.resolvers import reverse, reverse_lazy # Basic usage - reverse a view on the default host url = reverse('homepage') # Output: '//www.example.com/' # Specify a different host url = reverse('api-endpoint', host='api') # Output: '//api.example.com/endpoint/' # Include view arguments url = reverse('user-profile', args=['johndoe'], host='www') # Output: '//www.example.com/users/johndoe/' # With keyword arguments url = reverse('user-profile', kwargs={'username': 'johndoe'}, host='www') # Output: '//www.example.com/users/johndoe/' # Custom scheme and port url = reverse('repo', args=['myrepo'], host='api', scheme='git', port=1337) # Output: 'git://api.example.com:1337/repos/myrepo/' # Host with dynamic parameters (for wildcard hosts) url = reverse('dashboard', host='user-sites', host_kwargs={'username': 'johndoe'}) # Output: '//johndoe.users.example.com/dashboard/' # Lazy evaluation for class-based views and module-level usage from django.views.generic import RedirectView class MyRedirectView(RedirectView): url = reverse_lazy('homepage', host='www') ``` -------------------------------- ### Define Dynamic Host Patterns with Negative Lookahead Source: https://github.com/jazzband/django-hosts/blob/master/docs/index.md Utilize negative lookahead in regular expressions to exclude specific hostnames, such as 'www', from a broader pattern. This allows for more precise routing rules. ```python from django_hosts import patterns, host host_patterns = patterns( "", host(r"(?!www)\\w+", "path.to.custom_urls", name="wildcard"), ) ``` -------------------------------- ### Use host_url Template Tag Source: https://github.com/jazzband/django-hosts/blob/master/docs/index.md Employ the host_url template tag to reverse URLs, specifying the URL name and optionally the host and additional arguments. It automatically falls back to the default host if not specified. ```html+django {% load hosts %} Home | Your Account | ``` -------------------------------- ### HostSiteManager for Site-Filtered Queries Source: https://context7.com/jazzband/django-hosts/llms.txt Implement `HostSiteManager` in your Django models to automatically filter querysets based on the current site, simplifying multi-tenant application development. ```python # mysite/models.py from django.db import models from django.contrib.sites.models import Site from django_hosts.managers import HostSiteManager class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() site = models.ForeignKey(Site, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) # Default manager objects = models.Manager() # Site-filtered manager - auto-detects 'site' or 'sites' field on_site = HostSiteManager() class Article(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.CASCADE) objects = models.Manager() # Specify related field path for nested relationships on_site = HostSiteManager('author__site') # Disable select_related for performance tuning on_site_no_prefetch = HostSiteManager('author__site', select_related=False) class Author(models.Model): name = models.CharField(max_length=100) site = models.ForeignKey(Site, on_delete=models.CASCADE) ``` -------------------------------- ### Rendered Admin Dashboard Link Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md The rendered output of the `host_url` template tag, showing a protocol-relative URL. ```html+django Admin dashboard ``` -------------------------------- ### Using Overridden url Tag Source: https://context7.com/jazzband/django-hosts/llms.txt After overriding Django's url tag, you can use the standard {% url %} syntax with host-aware capabilities. This includes using the DEFAULT_HOST or specifying host parameters. ```django Home API Your Dashboard ``` -------------------------------- ### Access Host Information and Reverse URLs in Views Source: https://context7.com/jazzband/django-hosts/llms.txt Access host-specific details like name, regex, urlconf, scheme, and port from `request.host`. Use `django_hosts.resolvers.reverse` to generate URLs for different hosts. ```python # mysite/views.py from django.shortcuts import render from django_hosts.resolvers import reverse def context_aware_view(request): """Access host information from the request object.""" # request.host contains the matched host object current_host = request.host # Access host properties host_name = current_host.name # e.g., 'api' host_regex = current_host.regex # e.g., r'api' host_urlconf = current_host.urlconf # e.g., 'mysite.api_urls' host_scheme = current_host.scheme # e.g., '//' or 'https://' host_port = current_host.port # e.g., '' or ':8080' # request.urlconf is also set to the matched host's urlconf assert request.urlconf == current_host.urlconf # Generate URLs for different hosts api_url = reverse('api-endpoint', host='api') admin_url = reverse('admin-dashboard', host='admin', scheme='https') return render(request, 'context.html', { 'current_host': host_name, 'api_url': api_url, 'admin_url': admin_url, }) ``` -------------------------------- ### Configure ROOT_HOSTCONF Setting Source: https://github.com/jazzband/django-hosts/blob/master/README.rst Set the ROOT_HOSTCONF setting in your Django settings to point to the module containing your host patterns. This tells django-hosts where to find your host configuration. ```python ROOT_HOSTCONF = "mysite.hosts" ``` -------------------------------- ### Rendered Links with Individual Scheme Override Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md The rendered output showing the effect of the `scheme` parameter, with one link using 'https' and the other using the default protocol-relative scheme. ```html+django John's dashboard FAQ ``` -------------------------------- ### Set SERVER_NAME for client.post() in Tests Source: https://github.com/jazzband/django-hosts/blob/master/docs/faq.md When using client.post() in tests with django-hosts, set the SERVER_NAME to the appropriate host to resolve failures. ```python client.post(..., SERVER_NAME="api-server.something") ``` -------------------------------- ### Use Overridden URL Tag Source: https://github.com/jazzband/django-hosts/blob/master/docs/index.md After overriding Django's default url tag, you can use it similarly to the host_url tag, simplifying URL reversing in templates. The host parameter can still be specified if needed. ```html+django Home | Your Account | ``` -------------------------------- ### Override Django's url Template Tag Source: https://context7.com/jazzband/django-hosts/llms.txt Configure django-hosts in settings.py to automatically override Django's {% url %} tag. This allows host-aware URL reversal without needing to load the hosts tag explicitly. ```python # settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # ... your context processors ], 'builtins': [ 'django_hosts.templatetags.hosts_override', # Add this line ], }, }, ] ``` -------------------------------- ### Reverse URL in Python View Source: https://github.com/jazzband/django-hosts/blob/master/docs/index.md Use the reverse function from django_hosts.resolvers in your Python views to generate URLs, similar to Django's built-in reverse function. Specify the URL name and the desired host. ```python from django.shortcuts import render from django_hosts.resolvers import reverse def homepage(request): homepage_url = reverse("homepage", host="www") return render(request, "homepage.html", {"homepage_url": homepage_url}) ``` -------------------------------- ### Generate Host-Aware URLs with host_url Template Tag Source: https://context7.com/jazzband/django-hosts/llms.txt The host_url template tag generates URLs with host awareness, similar to Django's {% url %} tag. It supports specifying hosts, schemes, ports, and view arguments. ```django {% load hosts %} Home Home Profile Article FAQ Dashboard Admin Dev API {% host_url 'homepage' host 'www' as homepage_url %} Home ``` -------------------------------- ### Define a Custom Callback Function Source: https://github.com/jazzband/django-hosts/blob/master/docs/callbacks.md Define a Python function that accepts the request object and any captured URL arguments. This function can modify the request or return an HttpResponse. ```python from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User def custom_fn(request, username): request.viewing_user = get_object_or_404(User, username=username) ``` -------------------------------- ### Custom Callbacks for Request Modification Source: https://context7.com/jazzband/django-hosts/llms.txt Define custom callbacks in Python to modify the request object before a view is called. These callbacks can attach user information or tenant details. ```python from django.shortcuts import get_object_or_404, redirect from django.http import HttpResponseForbidden from django.contrib.auth.models import User from mysite.models import Tenant def attach_user(request, username): """Attach a user object to the request based on subdomain.""" request.viewing_user = get_object_or_404(User, username=username) # Return None to continue processing normally return None def attach_tenant(request, tenant_slug): """Multi-tenant callback that attaches tenant and checks access.""" tenant = get_object_or_404(Tenant, slug=tenant_slug) request.tenant = tenant # Check if tenant is active if not tenant.is_active: return HttpResponseForbidden("This tenant is not active") # Return None to continue to the view return None def redirect_old_subdomain(request, old_name): """Redirect from old subdomain to new location.""" return redirect(f'https://www.example.com/legacy/{old_name}/') ``` ```python # mysite/hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns ('', host(r'www', settings.ROOT_URLCONF, name='www'), # User subdomain with callback host( r'(?P\w+)', 'mysite.user_urls', callback='mysite.callbacks.attach_user', name='user-sites', ), # Multi-tenant subdomain host( r'(?P[\w-]+)', 'mysite.tenant_urls', callback='mysite.callbacks.attach_tenant', name='tenant', ), ) ``` -------------------------------- ### View Using Attached User Data Source: https://context7.com/jazzband/django-hosts/llms.txt A Django view that accesses user data attached to the request object by a custom callback. ```python # mysite/views.py from django.shortcuts import render def user_dashboard(request): """View that uses the attached user from callback.""" # request.viewing_user was set by the callback posts = request.viewing_user.posts.all() return render(request, 'dashboard.html', { 'viewing_user': request.viewing_user, 'posts': posts, }) ``` -------------------------------- ### Save Host URL to Template Variable Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Use the `host_url` template tag to save a generated URL to a template variable for later use, such as in an anchor tag's href attribute. This is useful for dynamic navigation elements. ```html+django {% load hosts %} {% host_url 'homepage' as homepage_url %} Home ``` -------------------------------- ### Override Django's URL Template Tag Source: https://github.com/jazzband/django-hosts/blob/master/docs/templatetags.md Automatically override Django's built-in `url` template tag by adding `'django_hosts.templatetags.hosts_override'` to your `TEMPLATES['OPTIONS']['builtins']` list. This avoids needing `{% load hosts %}` in every template. ```python TEMPLATES = [ { # ... other settings 'OPTIONS': { 'builtins': [ 'django_hosts.templatetags.hosts_override', ], }, }, ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.