Anonymous Django
Anonymous Django

Reputation: 11

How to enrich the Django request object with extended functions?

In my Django project, I have a situation where different views communicate via a request session data as follows:

def view_one(request):
    ...
    request.session['my_session_key'] = data
    ...

def view_two(request):
    ...
    data = request.session['my_session_key']
    ...

However, this has the following problems:

In Kotlin (which I'm more familiar with), one way to solve this would be using an extension function, like so:

var Request.my_session_key: Int
  get() = this.session['my_session_key']
  set(value) { this.session['my_session_key'] = value }

This way, I could now write my views as follows:

def view_one(request):
    ...
    request.my_session_key = data
    ...

def view_two(request):
    ...
    data = request.my_session_key
    ...

Is there any way to accomplish something similar in Python or with Django? Or, alternatively, taking a step back, what would be the best way to organize the data stored in a Django session across multiple views?

Upvotes: 1

Views: 115

Answers (0)

Related Questions