简体   繁体   English

将Django表单值传递给html

[英]passing django form values to html

I am working on a Django project and I have a form with a username field. 我正在处理Django项目,并且有一个带有用户名字段的表单。 I am trying to pass the username (just the value not the whole field that is given by form.username) from the form using form.fields['username'] but I get the following error: 我试图使用form.fields ['username']从表单传递用户名(只是值,而不是form.username给出的整个字段),但是出现以下错误:

Could not parse the remainder: '['username']' from 'form.fields['username']'

my html is: 我的html是:

{{form.fields['username']}}

and my form is : 我的表格是:

class RegisterationForm (forms.Form):

    first_name = forms.CharField(initial = 'eg. John',widget=forms.TextInput(attrs={'class' : 'form-control'}))
    last_name = forms.CharField(initial = 'eg. lennon',widget=forms.TextInput(attrs={'class' : 'form-control'}))
    username = forms.CharField(initial = 'eg. J.Lennon',widget=forms.TextInput(attrs={'class' : 'form-control'}))
    email = forms.EmailField(initial = 'form: example@something.com',widget=forms.TextInput(attrs={'class' : 'form-control'}))
    password = forms.CharField(initial = '******',widget=forms.TextInput(attrs={'class' : 'form-control'}))
    password2 = forms.CharField(initial = '******',widget=forms.TextInput(attrs={'class' : 'form-control'}))

My form is not bounded but since it has initial value I was expecting to see the initial value in the form.fields['username'] but I still get an error. 我的表单不受限制,但是由于它具有初始值,因此我期望在form.fields ['username']中看到初始值,但是仍然出现错误。 I have passed the form from the view function btw. 我已经通过视图函数btw传递了表单。 (when I just put {{form}} I do get the whole form on my HTML) (当我将{{form}}放到HTML上时,确实可以得到整个表格)

The correct way to do it is {{form.NAME_OF_THE_FIELD}} so for you it should be {{form.username}} 正确的方法是{{form.NAME_OF_THE_FIELD}}因此对您来说应该是{{form.username}}

Edit: 编辑:

Then to access username value it should be {{ form.username.value }} 然后,要访问用户名值,它应该是{{ form.username.value }}

As @ddalu5 mentioned the right command for the HTML is 正如@ ddalu5提到的,正确的HTML命令是

{{from.username.value}}

It is funny how I could not find that anywhere. 真有趣,我怎么都找不到。

{{form.fields['username']}} is invalid django template syntax. {{form.fields['username']}}是无效的Django模板语法。 You should use {{ form.name_of_field }} instead. 您应该改用{{ form.name_of_field }}

Check django doc about render form fields manually . 手动检查有关渲染表单字段的 django文档。

You can't do dict lookup in django template using [] , there's only . 您无法使用[]在django模板中进行字典查询,只有. lookup. 抬头。 Check django doc about the sequence of dot lookup in django template . 有关django模板中点查找的顺序,请查阅django doc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM