This question might be broad, but I have recently started using Python and MongoDB, and started building an application using Django. So, please guide me.
I'm using Django, but since there is no official integration with MongoDB; I'm directly using PyMongo for database operations. Thus, my models.py file is fully empty. I'm using Django for HTTP page routing and for similar functions that do not need access to a database.
My application has a /login, and a /profile page. The user logs in at the /login page, if the credentials are valid, I want the user to be redirected to /profile page and display his details like Name, Email etc. I want the user's session to be stored until the cookies in the browser are cleared or set an expiry for the session.
If the user tries to access /profile page directly, I want to validate the session and redirect the user to the /login page if needed or display the details otherwise.
I don't know how the HTTP sessions and cookies work. I've read the web for information, but I haven't understood clearly. I've also gone through some Stack Overflow links below, but they exactly don't fit my need.
- Login to website using python
- How do I start a session in a Python web application?
- simple implementation of sessions in python?
Here is my code:
/login:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
client = MongoClient('mongodb://djangouser:djangopass@1.1.1.1:27017/djangodb')
db = client.djangodb
newCollection = db.regdata
loginCheck = newCollection.find_one({"email": email, "password": password})
client.close()
if loginCheck != None:
return HttpResponseRedirect('/profile/')
else:
return http.HttpResponse("Invalid credentials!")
else:
return render(request, 'login.html')
/profile:
def profile(request):
return http.HttpResponse("Ok!")
Now, what code should I write in /login & /profile blocks to validate cookies, manage sessions, and everything?