1👍
✅
Because the SuppliersForm
is closely related to the Company
Model, it’ll be best to make use of a ModelForm. A ModelForm will reuse the field definitions in its associated Model and can handle the creation of the database object.
You should also make the company_rating
field on the Company model a choice field, similar to the company_status
and company_size
fields.
models.py
class Company(models.Model):
...
COMPANY_RATING_CHOICES = (
('Perfect', 'Perfect'),
('Average', 'Average'),
('Bad', 'Bad'),
)
...
company_rating = models.CharField(choices=COMPANY_RATING_CHOICES, max_length=20, default='Perfect', null=True)
forms.py
from django.utils.translation import gettext_lazy as _
class SuppliersForm(forms.ModelForm):
class Meta:
model = Company
fields = '__all__'
labels = {
'company_name': _('Company Name'),
'company_number': _('Company Number'),
'company_vat_number': _('Company Vat Number'),
'company_status': _('Company Status'),
'company_size': _('Company Size'),
'company_rating': _('Company Rating'),
}
views.py
def suppliers_create(request):
if request.method == 'POST':
form = SuppliersForm(request.POST)
if form.is_valid():
form.save()
return redirect('/suppliers')
else:
form = SuppliersForm()
return render(request, 'suppliers/suppliers_create.html', {'form': form})
Source:stackexchange.com