Cleaning form fields

In order to verify that the provided image URL is valid, we will check that the filename ends with a .jpg or .jpeg extension to only allow JPEG files. As you saw in the preceding chapter, Django allows you to define form methods to clean specific fields using the clean_<fieldname>() notation. This method is executed for each field, if present, when you call is_valid() on a form instance. In the clean method, you can alter the field's value or raise any validation errors for this specific field when needed. Add the following method to ImageCreateForm:

def clean_url(self):    url = self.cleaned_data['url']    valid_extensions = ['jpg', 'jpeg']    extension = url.rsplit('.', 1)[1].lower()    if extension not in valid_extensions: raise ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.