Welcome back to CodeYourCraft! Today, we're going to dive into the Session Framework in Django. This powerful tool helps us manage user data across multiple requests, making our web applications more dynamic and user-friendly. Let's get started!
π‘ Pro Tip: Sessions are a way to store data for a user across multiple requests. They are essential for maintaining state in web applications.
First, let's create a simple session.
from django.contrib.sessions.models import Session
def create_session(request):
session = Session()
session.session_key = request.session.session_key # assign session key
session.save()
request.session = sessionπ Note: The Session model handles session management in Django. The session_key is unique for each session.
To access and modify session data, use the request.session object.
def set_and_get_session_data(request):
request.session['name'] = 'John Doe' # set session data
name = request.session.get('name') # get session data
print(name) # outputs: John Doeπ Note: The get() method returns the session data if it exists, and None if it doesn't.
By default, Django sessions are stored in the database and expire after two weeks of inactivity. However, you can customize this behavior.
from django.conf import settings
from django.utils.timezone import timedelta
def set_session_timeout(request, timeout=timedelta(days=30)):
request.session.session_timeout = timeoutπ‘ Pro Tip: Adjust the session timeout to suit your application's needs.
To delete a session, use the delete() method.
def delete_session(request):
request.session.flush()
request.session.delete()π Note: The flush() method removes all session data, and the delete() method deletes the session from the database.
What is the purpose of the `Session` model in Django?
Stay tuned for more in-depth sessions with Django! We'll discuss how to use sessions for user authentication and explore advanced techniques. Happy coding! π