Ayush
Ayush

Reputation: 167

Using Django session key to use request sessions between views

Is it a good idea to store django _session_key in another model as an identifier for specific session.

I am using django _session_key to store a unique session inside a view and then I am saving the _session_key in another object .

def myview(request):

    if request.method == "POST":
        myform = Myform(request.form)

        if myform.is_valid():
            name = myform.cleaned_data['name']
            title = myform.cleaned_data['title']
            author_session = request.session._session_key
            # Creating a model object
            model1(name=name, title=title, author_session=author_session).save()

            return HttpResponseRedirect(reverse('myview2', 
                                                 kwargs={'name':model1.name}))
        else:
            # Some renders
    else:
        # Some other renders

def myview2(request, name):

    obj1 = model1.objects.get(name=name)

    if request.session._session_key == obj1.author_session:
         # Some render
    else:
         # Some other render

Now ,I am thinking is this a good idea to use _session_key as unique identity for sessions between different views . Is there any other way to identify unique session between views ?

P.S- I have read that using _session_key is generally disregarded.

Also please suggest how to write tests for the sessions between views

Upvotes: 0

Views: 422

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

No, this is entirely backwards. You should store the key of the model1 instance in the session in the first view, and get it out in the second.

Upvotes: 2

Related Questions