我有一个名为Customer的模型和名为Customer的modelForm,但在我的表单中,我需要的字段多于Model中的字段。例如,我想在我的ModelForm中使用confPass字段。 型号代码:
class Customer(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, unique=True)
mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10)
state = models.CharField(choices=STATES, max_length=2)
city = models.CharField(max_length=20)
password = models.CharField(max_length=256)
def __str__(self):
return self.email
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'placeholder': 'Enter Name', 'class': 'form-control'})
self.fields['email'].widget.attrs.update({'placeholder': 'Enter Email', 'class': 'form-control'})
self.fields['mobile_no'].widget.attrs.update({'placeholder': 'Enter Mobile Number ', 'class': 'form-control'})
self.fields['state'].widget.attrs.update({'class': 'form-control'})
self.fields['city'].widget.attrs.update({'placeholder': 'Enter City', 'class': 'form-control'})
self.fields['password'].widget.attrs.update({'class': 'form-control'})
答案 0 :(得分:1)
只需将该字段添加到您的CustomerForm
课程,并将其添加到fields
列表中:
class CustomerForm(ModelForm):
confPass = forms.CharField()
class Meta:
model = Customer
fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password', 'confPass']