关于非常规地址的Django URL模式及指定地址正则表达式的咨询
Hey there! Let's tackle your two Django URL questions clearly and directly:
When dealing with "unconventional" addresses (think paths containing special characters like ~, @, ., or custom structured segments), Django's re_path (which uses regular expressions) is your go-to tool—it’s far more flexible than the simpler path function with built-in path converters.
Here are practical examples for common unconventional scenarios:
from django.urls import re_path from . import views urlpatterns = [ # Match user profiles with usernames that include ~, _, or numbers re_path(r'^user/(?P<username>[a-zA-Z0-9_~]+)/profile/$', views.user_profile, name='user-profile'), # Match document paths with version numbers (like v1.2) in the filename re_path(r'^files/(?P<doc_name>[a-zA-Z0-9_\.]+)/$', views.serve_document, name='serve-document'), # Match contact paths using email addresses (which include @ and .) as parameters re_path(r'^contact/(?P<email>[a-zA-Z0-9_\.@]+)/$', views.contact_user, name='contact-user'), ]
A quick breakdown:
(?P<param_name>pattern)creates a named capture group, which passes the matched value directly to your view function as a keyword argument.- To allow specific special characters, just add them to the regex character set (
[]). Note: If you need to include-in the allowed characters, place it at the start or end of the set to avoid confusing it with a range operator (likea-z). - For ultra-flexible (but cautious) matching, you can use
.*to match any character sequence, but always try to make your regex as specific as possible to avoid unintended matches.
host:8000/?page=1 First, a key clarification: The ?page=1 part is a query parameter, not part of the URL path itself. Django automatically parses query parameters into request.GET—you don't need to include them in your URL pattern at all!
All you need to do is match the root path (/), like this:
from django.urls import path from . import views urlpatterns = [ # Match the root URL (host:8000/) path('', views.index, name='index'), ]
Then, in your view function, you can access the page parameter easily:
def index(request): # Get the page number from the query string, default to 1 if it's missing page_number = request.GET.get('page', 1) # Your logic here (e.g., paginate content) return render(request, 'index.html', {'page': page_number})
If you want to redirect users to host:8000/?page=1 from another view, you can do this:
from django.shortcuts import redirect from django.urls import reverse def redirect_to_paginated_home(request): # Build the URL with the query parameter home_url = f"{reverse('index')}?page=1" return redirect(home_url)
内容的提问来源于stack exchange,提问作者Christopher_Okoro

