【问题标题】:How to have additional field besides the fields in the model in ModelForm如何在 ModelForm 中除了模型中的字段之外还有其他字段
【发布时间】:2018-04-16 17:50:25
【问题描述】:

我有一个名为 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'})

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    只需将该字段添加到您的 CustomerForm 类并将其包含在 fields 列表中:

    class CustomerForm(ModelForm):
        confPass = forms.CharField()
        class Meta:
            model = Customer
            fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password', 'confPass']
    

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 1970-01-01
      • 2020-07-03
      • 2020-02-04
      • 2011-01-14
      • 1970-01-01
      • 2021-10-10
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多