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

时间:2015-08-17 14:06:16

标签: 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=(""))

它显示错误,返回'request'未定义。

1 个答案:

答案 0 :(得分:4)

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

def view(request):
    initial_name = request.session['name']
    form = UpdateForm(initial={'name': initial_name})

您的表格:

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=(""))