Форма модели Django не проходит проверку при заданных в модели значениях по умолчанию
Предыстория: Я пытаюсь реализовать новый поток регистрации пользователей, который добавляет шаг проверки (с использованием OTP) для их номера телефона и адреса электронной почты. Несколько форм отправляются через JS и редактируются в views.py def registration().
Цель: Проверить все формы и затем сохранить их
Проблема:
Формы моих клиентов не проходят валидацию. Я получаю следующие ошибки:
{'status': [ValidationError(['This field is required.'])], 'customer_number': [ValidationError(['This field is required.'])], 'payment_term': [ValidationError(['This field is required.'])], 'discount': [ValidationError(['This field is required.'])]}
Что я пробовал: Я пытался использовать как форму модели, так и форму без модели, но безрезультатно. При использовании немодельной формы я получаю сообщение "Объект не имеет функции сохранения", а при использовании модельной формы я получаю вышеуказанную ошибку. Я не уверен, почему я не могу отправить эту форму с пустыми полями, поскольку все они установлены по умолчанию.
models.py
class Customer(BaseModel):
status = models.CharField("Status", max_length=2, choices=STATUS_OPTIONS, default="A")
customer_name = models.TextField("Customer Name", max_length=100, unique=True)
customer_number = models.TextField(max_length=19, unique=True, default=get_customer_number)
phone_number = models.CharField(max_length=16, unique=True)
payment_term = models.CharField("Payment Terms", max_length=4, choices=PAYMENT_TERM_OPTIONS, default="100P")
discount = models.DecimalField("Discount", max_digits=2, decimal_places=2, default="0")
views.py
forms.py
class CustomerCreateForm(forms.Form):
customer_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"Customer Name"}))
phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"Company Phone Number"}))
address_type = forms.ChoiceField(choices=ADDRESS_TYPE_OPTIONS)
street_address_1 = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"Street Address"}))
street_address_2 = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"Street Address 2 (optional)"}))
city = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"City"}))
region = forms.ChoiceField(choices=REGIONS_OPTIONS)
postal_code = forms.CharField(widget=forms.TextInput(attrs={'placeholder':"Postal Code"}))
country = forms.ChoiceField(choices=COUNTRY_OPTIONS)
account_type = forms.ChoiceField(choices=[('',"Select Option"), ('New Company','Yes, our Company is new to ICS and want to set up a brand new account'), ('New User','No, our Company has an account but our team is growing and we need to add a new user to our existing account'), ('Login', "No, I'm lost and just want to login")])
def __init__(self, *args, **kwargs):
super(CustomerCreateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.fields['street_address_2'].required = False
self.helper.form_show_labels = False
self.helper.form_method = 'POST'
self.helper.attrs = {
'novalidate': ''
}
class CustomerCreateModelForm(forms.ModelForm):
class Meta:
model = Customer
exclude = ['history',]