如何创建特定于用户的 django url?
How can I create a django url specific to a user?
我有兴趣为每个用户定制我的网址,比如
username.mysite.com/home
但我不确定如何用 django 做到这一点。
我也很好奇这在开发中是否可行(以便有 username.localhost:8000/home
)。
谢谢。
还有一个办法。您可以做的是让中间件获取 url,解析子域,然后呈现用户个人资料页面。
这是假设您使用的是自定义个人资料页面而不是默认个人资料页面。
#in yourapp.middleware
from django.contrib.auth.models import User
import logging
import yourapp.views as yourappviews
logger = logging.getLogger(__name__)
class AccountMiddleware(object):
def process_request(self, request):
path = request.META['PATH_INFO']
domain = request.META['HTTP_HOST']
pieces = domain.split('.')
username = pieces[0]
try:
user = User.objects.get(username=username)
if path in ["/home","/home/"]:
return yourappviews.user_profile(request, user.id)
#In yourapp.views.py
def user_profile(request,id):
user = User.objects.get(id=id)
return render(request, "user_profile.html", {"user": user})
#In settings.py
MIDDLEWARE_CLASSES = (
#... other imports here
'yourapp.middleware.AccountMiddleware'
)
我有兴趣为每个用户定制我的网址,比如
username.mysite.com/home
但我不确定如何用 django 做到这一点。
我也很好奇这在开发中是否可行(以便有 username.localhost:8000/home
)。
谢谢。
还有一个办法。您可以做的是让中间件获取 url,解析子域,然后呈现用户个人资料页面。
这是假设您使用的是自定义个人资料页面而不是默认个人资料页面。
#in yourapp.middleware
from django.contrib.auth.models import User
import logging
import yourapp.views as yourappviews
logger = logging.getLogger(__name__)
class AccountMiddleware(object):
def process_request(self, request):
path = request.META['PATH_INFO']
domain = request.META['HTTP_HOST']
pieces = domain.split('.')
username = pieces[0]
try:
user = User.objects.get(username=username)
if path in ["/home","/home/"]:
return yourappviews.user_profile(request, user.id)
#In yourapp.views.py
def user_profile(request,id):
user = User.objects.get(id=id)
return render(request, "user_profile.html", {"user": user})
#In settings.py
MIDDLEWARE_CLASSES = (
#... other imports here
'yourapp.middleware.AccountMiddleware'
)