如何在 python django 中使用会话变量作为表单字段的默认值?

mar*_*922 0 python django

在forms.py中,

class UpdateForm(forms.Form):
   n1 = request.session['name']
   name = forms.CharField(widget=forms.TextInput(attrs={
           'style':'margin-bottom:10px; width:600px; height:50px ;align:right',
           'required':'',
           'value':n1,
           'placeholder':'Name of Institute',
           'class':'form-control'}), label=(""))
Run Code Online (Sandbox Code Playgroud)

它显示返回“请求”未定义的错误。

sch*_*ngt 5

您可以在表单上使用初始 kwarg。这是文档。您的观点:

def view(request):
    initial_name = request.session['name']
    form = UpdateForm(initial={'name': initial_name})
Run Code Online (Sandbox Code Playgroud)

您的表格:

class UpdateForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(
            attrs={'style':'margin-bottom:10px; width:600px; height:50px ;align:right',
                   'required':'',
                   'placeholder':'Name of Institute',
                   'class':'form-control'}),
            label=(""))
Run Code Online (Sandbox Code Playgroud)