我有以下代码,我收到一条错误消息:“User对象没有属性POST”
def login (request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(user)
return render(request, 'base_in/base_in.html', {})
else:
return render(request, 'signupapp/error.html', {'message':'the acount is not active'})
else:
return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'})
我也尝试了这段代码并得到了另一个错误:“login()需要1个位置参数但是2个被赋予”
def login (request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(user)
return render(request, 'base_in/base_in.html', {})
else:
return render(request, 'signupapp/error.html', {'message':'the acount is not active'})
else:
return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'})
我做错了什么?基于django教程,它应该正常工作:
https://docs.djangoproject.com/en/1.9/topics/auth/default/#how-to-log-a-user-in
答案 0 :(得分:3)
您尝试拨打login
的{{1}}时发生了什么事,但您也定义了自己的from django.contrib.auth
函数,这里有一种名称冲突。
您应该将其重命名为其他内容,例如login()
login_view()
如果您不想重命名,可以使用其他名称导入Django from django.contrib.auth import authenticate, login
def login_view(request): # If you call it login,
# you get conflict with login imported aove
# The rest of your code here
# now if you call login(user), it will use the correct one,
# i.e. the one imported from django.contrib.auth
,例如
login
答案 1 :(得分:0)
我建议先添加登录表单
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)#hides password on input
然后
from django.http import HttpResponseRedirect,HttpResponse
from django.contrib.auth import authenticate, login
.
.
def user_log(request):
#if you add request.method=='POST' is it a bug i dont know y
if request.method:
form = LoginForm(request.POST)
if form.is_valid():
cleandata=form.cleaned_data
#authenticate checks if credentials exists in db
user=authenticate(username=cleandata['username'],
password=cleandata['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect("your template")
else:
return HttpResponseRedirect("your templlate")
else:
return HttpResponse("Invalid login")
else:
form=LoginForm()
return render(request, 'registration/login.html',{'form':form})
答案 2 :(得分:-1)
login is working but i want to login using model value like username and password
def login(request):
if request.method=='POST':
username1=request.POST['username']
password1=request.POST['password']
user=authenticate(username=username1,password=password1)
if user is not None:
if user.is_active:
dj_login(request, user)
return render(request,"products/dashboard.html")
else:
print("user is not active")
else:
messages.error(request,'Username and Password is invalid')
return render(request,'products/login.html')
else:
return render(request,'products/login.html')