[英]Is there a way to pass a list to determine fields in a django form?
I have a list determined by an admin for which fields the user should be able to fill out.我有一个由管理员确定的列表,用户应该能够填写哪些字段。 I have tried passing a subset of my fields into the fields variable in my forms.py but all the fields are still rendered in the template.
我尝试将我的字段子集传递到我的 forms.py 中的 fields 变量中,但所有字段仍呈现在模板中。
forms.py forms.py
class myForm(forms.ModelForm):
myList = ['field1']
field1 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
field2 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = myModel
fields = myList
Im just rendering my form with {{ form }}
in my html.我只是在我的 html 中使用
{{ form }}
渲染我的表单。 I dont get any errors but my app renders all the fields instead of just the ones in my list我没有收到任何错误,但我的应用程序呈现所有字段,而不仅仅是列表中的字段
try this code below:试试下面的代码:
class myModel(models.Model): # Your Model
field1 = models.CharField( .. )
field2 = models.CharField( .. )
class myForm(forms.ModelForm): # Your Form Model
class Meta:
model = myModel
fields = ['field1']
widgets = {
'field1': forms.TextInput( attrs={'class': 'form-control'} )
}
refer to https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/参考https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.