Django - Access request.session in form
I am calling a form as follows, then passing it to a templa开发者_Python百科te:
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?
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
精彩评论