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.

Making Fields Optional - 图1

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):

  1. # \myclub_root\events\models.py
  2. 1 class Venue(models.Model):
  3. 2 name = models.CharField('Venue Name', max_length=120)
  4. 3 address = models.CharField(max_length=300)
  5. 4 zip_code = models.CharField('Zip/Post Code', max_length=12)
  6. 5 phone = models.CharField('Contact Phone', max_length=20, blank=True)
  7. 6 web = models.URLField('Web Address', blank=True)
  8. 7 email_address = models.EmailField('Email Address', blank=True)
  9. 8
  10. 9 def __str__(self):
  11. 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:

  1. (env_myclub) ...\myclub_root> python manage.py makemigrations
  2. Migrations for 'events':
  3. events\migrations\0003_auto_20200523_0740.py
  4. - Alter field email_address on venue
  5. - Alter field phone on venue
  6. - Alter field web on venue

Then run the migrate command to migrate the changes to the database:

  1. (env_myclub) ...\myclub_root> python manage.py migrate
  2. Operations to perform:
  3. Apply all migrations: admin, auth, contenttypes, events, sessions
  4. Running migrations:
  5. 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).

Making Fields Optional - 图2

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.