models.py
from django.db import models
class user(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=100, unique=True)
forms.py
from django import forms
from second_app.models import user
class NewUserForm(forms.ModelForm):
class Meta:
model = user
fields = '__all__'
在不从模型继承的普通forms.py
中,您可以使用field = forms.CharField(widget=forms.HiddenInput)
指定输入字段将如何显示给用户。当forms.py
继承models.py
中定义的类时,如何才能做到这一点?
答案 0 :(得分:1)
您可以使用此元widgets
选项:
from django import forms
from second_app.models import user
class NewUserForm(forms.ModelForm):
class Meta:
model = user
fields = '__all__'
widgets = {
'field_name': forms.HiddenInput(),
}
答案 1 :(得分:1)
您可以使用__init__
方法:
def __init__(self, *args, **kwargs):
super(NewUserForm, self).__init__(*args, *kwargs)
self.fields['fieldname'].widget = forms.HiddenInput()
您可以更改有关该字段的任何内容..例如。在表单显示时您可能希望以不同方式决定的必需,选择和许多其他内容。您也可以在此处删除表单中的字段,或添加您可能只想有条件地包含的字段...例如:
del self.fields['fieldname']
if some_condition:
field['new_fieldname'] = forms.CharField()