10.4. Forms Model
10.4.1. Model
File myproject/shop/models.py
:
from django.db import models
class Customer(models.Model):
firstname = models.CharField(verbose_name=_('First Name'), max_length=30)
lastname = models.CharField(verbose_name=_('Last Name'), max_length=30, db_index=True)
birthdate = models.DateField(verbose_name=_('Birthdate'), null=True, blank=True)
def __str__(self):
return f'{self.firstname} {self.lastname}'
class Meta:
verbose_name = _('Customer')
verbose_name_plural = _('Customers')
10.4.2. Form
File myproject/shop/forms.py
:
from django import forms
from shop.models import Customer
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = ['firstname', 'lastname']
def clean_firstname(self):
firstname = self.cleaned_data['firstname']
if '@' in firstname:
raise forms.ValidationError("Character @ is not allowed in first name")
else:
return firstname
10.4.3. View
File myproject/shop/views.py
:
from .forms import CustomerForm
from django.views.generic import FormView
class CustomerCreate(FormView):
template_name = 'shop/customer-create.html'
form_class = CustomerForm
success_url = '/customer/create/success/'
def form_valid(self, form):
Customer.objects.create(
firstname=form.cleaned_data['firstname'],
lastname=form.cleaned_data['lastname'])
return super().form_valid(form)
10.4.4. Template
File myproject/shop/templates/shop/.py
:
<form method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Send message">
</form>