Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Access request.session in form

I am calling a form as follows, then passing it to a template:

f = UserProfileConfig(request)

I need to be able to access the request.session within the form... so first I tried this:

class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.tester = request.session['some_var']

    username = forms.CharField(label='Username',max_length=100,initial=self.tester)

This didn't work, I gather, because of when the form is constructed compared to setting the username charfield.

So, next I tried this:

class UserProfileConfig(forms.Form):

def __init__(self,request,*args,**kwargs):
    super (UserProfileConfig,self).__init__(*args,**kwargs)
    self.a_try = forms.CharField(label='Username',max_length=100,initial=request.session['some_var'])


username = self.a_try

To no avail.

Any other ideas?

like image 621
Brant Avatar asked Mar 03 '10 18:03

Brant


People also ask

How can I get session data in Django?

Using database-backed sessions If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

What is request session in Django?

Sessions are the mechanism used by Django (and most of the Internet) for keeping track of the "state" between the site and a particular browser. Sessions allow you to store arbitrary data per browser, and have this data available to the site whenever the browser connects.

Where is session data typically stored in a Django application?

Setting Up Sessions By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache.

How do I end a session in Django?

As of Django 1.8, any call to flush() will log out the user. From the docs: Changed in Django 1.8: Deletion of the session cookie is a behavior new in Django 1.8. Previously, the behavior was to regenerate the session key value that was sent back to the user in the cookie.


2 Answers

Try this:

class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.fields['username'] = forms.CharField(label='Username',max_length=100,initial=request.session['some_var'])

I find this article about dynamic forms very helpful.

like image 61
Felix Kling Avatar answered Oct 14 '22 07:10

Felix Kling


I am so surprised that Django use session in form is so hard. sometimes we really need use session data in form to valid fields.

I create a small project can solve this. django-account-helper

example code:

from account_helper.middleware import get_current_session

Class YourForm(forms.Form):

    def clean(self):
        session = get_current_session()
        if self.cleaned_data.get('foo') == session.get('foo'):
            # do something
            pass

        #... your code
    pass
like image 1
9nix00 Avatar answered Oct 14 '22 08:10

9nix00