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?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With