Making Fields Optional
Enter Venue Name, Address and Zip/Post Code in the blank form, but leave the Contact Phone, Web Address and Email Address fields blank. Click “Save”. Your screen should look something like Figure 7.5. This error occurred because, by default, all model fields are required.
Figure 7-5: By default, all fields are required when adding records in the admin.
This is not always what you want. For example, a venue might not have a web address, and a venue may provide an email address or a phone number, but not both. To correct this error, we need to update the Venue
model (changes in bold):
# \myclub_root\events\models.py
1 class Venue(models.Model):
2 name = models.CharField('Venue Name', max_length=120)
3 address = models.CharField(max_length=300)
4 zip_code = models.CharField('Zip/Post Code', max_length=12)
5 phone = models.CharField('Contact Phone', max_length=20, blank=True)
6 web = models.URLField('Web Address', blank=True)
7 email_address = models.EmailField('Email Address', blank=True)
8
9 def __str__(self):
10 return self.name
You can see in lines 5, 6 and 7 I have set the blank
field option to True
. The default is False
, which makes the field required.
As we have changed a model, we need to update the database. First, run makemigrations
:
(env_myclub) ...\myclub_root> python manage.py makemigrations
Migrations for 'events':
events\migrations\0003_auto_20200523_0740.py
- Alter field email_address on venue
- Alter field phone on venue
- Alter field web on venue
Then run the migrate
command to migrate the changes to the database:
(env_myclub) ...\myclub_root> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, events, sessions
Running migrations:
Applying events.0003_auto_20200523_0740... OK
Restart the development server and log in to the admin. Click on the “Add” link next to the Venues listing to open the edit form (Figure 7-6).
Figure 7-6: The venue edit form with optional fields.
The first thing you should notice is that the Contact Phone, Web Address and Email Address field names are no longer in bold text. This indicates these fields are no longer required. Enter some information for Venue Name, Address and Zip/Post Code and click “Save”. You should have no problem entering the new venue with the blank fields. Django will display a success message and switch back to the venue change list view.