我有一个应用程序,允许用户创建个人资料并登录。
当用户登录时,他被重定向到127.0.0.1:8000/profile /
问题是,我想通过将用户的用户名添加到URL的末尾来自定义URL,例如127.0.0.1:8000/profile/michael
这是一个与我相似的问题
Django - after login, redirect user to his custom page --> mysite.com/username
“获取用户名,然后对自定义网址执行HttpResponseRedirect。”
我似乎无法弄清楚如何将用户名作为HttpResponseRedirect的参数传递,以便正确处理自定义URL。
return HttpResponseRedirect('/profile/?username=%s' % (username, request.path))
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
person = Person.objects.get(user=request.user)
return render(request,'profile.html',{'person':person})
我的网址
url(
r'^profile/$',
'pet.views.Profile',
name = 'Profile'
),
NEW
my views.py
def LoginRequest(request):
if request.user.is_authenticated():
username = User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
username= User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
return render(request, 'login.html',{'form': LoginForm()})
url(
r'^login/$',
'pet.views.LoginRequest',
name = 'LoginRequest'
),
url(
r'^profile/(?P<username>\w+)/$',
'pet.views.Profile',
name = 'Profile'
),
def Profile(request,username):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user__username=username)
return render(request,'profile.html',{'board':board ,'person':person})
答案 0 :(得分:3)
这将是您的重定向网址的正确正则表达式,即。不要修改你的那个。
url(r'^profile/(?P<username>\w+)/$', 'pet.views.myprofileview', name="detail_profile")
然后将参数传递给重定向:
url = reverse('detail_profile', kwargs={'username': profile.firstname})
return HttpResponseRedirect(url)
这导致还必须定义新视图:
def myprofileview(request, username):
person = Person.objects.get(user = request.user)
return render(request,'profile.html',{'person':person})
这会消除一个视图中的两个行为,我觉得这非常好!
我们这样做是因为它是HttpResponseRedirect
接受的字符串,因此我们必须相应地构建它。
这会重定向到myprofileview
视图和“样式”,如果你可以称之为你的网址/profile/michael/
。
答案 1 :(得分:1)
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': request.user.username}))
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': username}))
return render(request, 'login.html',{'form': LoginForm()})