python Django - 以表单访问 request.session

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2373867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:29:24  来源:igfitidea点击:

Django - Access request.session in form

pythondjangodjango-forms

提问by Brant

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:

我需要能够访问表单中的 request.session ......所以首先我尝试了这个:

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?

还有其他想法吗?

回答by Felix Kling

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 formsvery helpful.

我发现这篇关于动态表单的文章非常有帮助。

回答by 9nix00

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.

我很惊讶 Django 在表单中使用 session 是如此困难。有时我们真的需要在表单中使用会话数据到有效字段。

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

我创建了一个小项目可以解决这个问题。 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