我正在使用DJango登录/身份验证功能。我使用Extending The Existing User Model方法使用配置文件扩展了它。
在“个人资料”中有一个名为 restrole 的变量。在下面的代码中, restrole 用于控制用户看到的NEXT屏幕(以及其上的数据):
def user_login(request):
if request.method == 'POST':
# First get the username and password supplied
username = request.POST.get('username')
password = request.POST.get('password')
# Django's built-in authentication function:
user = authenticate(username=username, password=password)
if user:
# Check it the account is active
if user.is_active:
# Log the user in.
login(request, user)
myprofile = user.userprofileinfo
restrole = myprofile.restrole
if restrole == 1:
return HttpResponseRedirect(reverse('authinduction:induct-owner'))
elif restrole == 2:
return HttpResponseRedirect(reverse('authinduction:induct-office'))
elif restrole == 3:
return HttpResponseRedirect(reverse('authinduction:induct-customer'))
elif restrole == 4:
return HttpResponseRedirect(reverse('authinduction:induct-field-work'))
else:
return HttpResponse("Unrecognized Role")
我可以从“请求”变量中获取数据
# First get the username and password supplied
username = request.POST.get('username') <<< data is returned
password = request.POST.get('password') <<< data is returned
当我执行其中一个分支时:
if restrole == 1:
return HttpResponseRedirect(reverse('authinduction:induct-owner'))
它转到正确的功能,但“请求”似乎没有任何与之关联的数据。获取“用户名”会导致获得“无”的值
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from authinduction.models import Mstrauthownerrdx
from django.contrib.auth.models import User
def inductowner(request):
username = request.POST.get('username') <<< does NOT work, returns "None"
user = User.objects.get(username=username) <<< causes a DoNotExist error here
解决此问题的最佳方法是什么?
TIA
@Alasdair - 感谢您的回复。这就是诀窍!我注意到表单本身访问用户登录信息,如下所示:
<input type="text" name="username" placeholder="Enter Your Logon Info">
如上所述,要获取用户名(按照您的注意进行POST),可以使用
username = request.POST.get('username')
在所有这些中,我一直看到“用户名”,但是 - 为了解决问题,一个用户“request.user”。为什么会这样?我问,因为我从未想过使用“request.user”来获取信息。如果有的话,我会使用“request.username”
答案 0 :(得分:0)
当您返回重定向响应时,Django会对该URL发出GET请求,因此POST数据不会发送到新URL。
由于您已在user_login
中登录了该用户,因此我会在下一个视图中从request
中提取该用户。
from django.contrib.auth.decorators import login_required
@login_required
def inductowner(request):
user = request.user
...
login_required
确保只有登录用户才能访问该视图,因此阻止匿名用户直接进入inductowner
视图。