To avoid repeating host-lookup logic (like fetching a Site or User object) in every view, you can define a callback function and pass it to the host() object via the callback parameter.
When a host matches, the callback is executed with the request object and any named arguments captured from the host regex.
Behavior based on return value:
- If the callback returns
None, processing continues and the view associated with the host's URLconf is called. - If the callback returns a
django.http.HttpResponse object, that response is returned immediately to the client, bypassing the view.
Important Considerations:
- URLconf Context: Callbacks are executed within the context of the specific URLconf assigned to that host. This means
django.urls.reverse might not find URLs defined in your default URLconf unless you explicitly provide the urlconf parameter. - Subdomain Conflicts: If using dynamic hosts (e.g.,
(?P<username>\w+)), ensure users cannot register names that conflict with static subdomains like www. - Error Handlers: Remember to add
handler404 and handler500 entries for any custom URLconfs you define.
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.conf import settings
from django_hosts import patterns, host
# 1. Define the callback function
def custom_fn(request, username):
# Attach data to the request for use in views
request.viewing_user = get_object_or_404(User, username=username)
# 2. Pass the callback path to the host() function
host_patterns = patterns(
"",
host(r"www", settings.ROOT_URLCONF, name="www"),
host(
r"(?P<username>\w+)",
"path.to.custom_urls",
callback="path.to.custom_fn",
name="with-callback",
),
)