Reputation: 11
def signin(request):
if request.method == "POST":
form = LoginForm(request.POST)
email_input = str(request.POST['email'])
password_input = str(request.POST['password'])
user_Qset = Profile.objects.filter(email = email_input)
if user_Qset is not None:
password_saved = str(user_Qset.values('password')[0]['password'])
if password_input == password_saved:
request.session['name'] = str(user_Qset.values('name')[0] ['name'])
request.session['email'] = str(user_Qset.values('email')[0]['email'])
request.session['password'] = str(user_Qset.values('password')[0]['password'])
return HttpResponse('login success.')
else:
return HttpResponse('locin failed, wrong password')
else:
return HttpResponse('login failed, wrong email address')
else:
form = LoginForm()
return render(request, 'registration/login.html', {'form': form})
I want to add cookies by using request.session
method but it doesn't work
How can I use it?
Upvotes: 0
Views: 7279
Reputation: 1177
As you may know, there is a huge difference between cookies & session. Cookies store data on the client side. Sessions use a cookie as a key, and associate it with the data that is stored on the server side.
It is usually better to use sessions instead of cookies because the data are hidden from the client, and you can easily set when the data expires to become invalid.
On the security side, if it was all built around cookies, a vicious user could change their cookies data send bad request to your website.
But if you want really use cookies, Django now handle direct cookie manipulation methods on the request and response objects.
You can do so as follow :
Views.py
def signin(request):
response = HttpResponse('login success.')
if request.method == "POST":
form = LoginForm(request.POST)
email_input = str(request.POST['email'])
password_input = str(request.POST['password'])
user_Qset = Profile.objects.filter(email = email_input)
if user_Qset is not None:
password_saved = str(user_Qset.values('password')[0]['password'])
if password_input == password_saved:
response.set_cookie('name', str(user_Qset.values('name')[0] ['name']))
response.set_cookie('email', str(user_Qset.values('email')[0]['email']))
response.set_cookie('password', str(user_Qset.values('password')[0]['password']))
return response
else:
return HttpResponse('locin failed, wrong password')
else:
return HttpResponse('login failed, wrong email address')
else:
form = LoginForm()
return render(request, 'registration/login.html', {'form': form})
Sources https://docs.djangoproject.com/en/dev/topics/http/sessions/
https://docs.djangoproject.com/en/dev/ref/request-response/
Upvotes: 1