ImageField
This class provides a specialized file upload field that validates uploaded files as images using the Pillow library. It ensures the uploaded data is a valid image format, such as GIF, JPG, or PNG, and automatically sets the appropriate HTML accept attribute for associated widgets. The class also annotates the file object with image metadata and MIME type information during the validation process.
Attributes
| Attribute | Type | Description |
|---|---|---|
| default_validators | list = [validators.validate_image_file_extension] | A list of validation functions applied to the field, initialized with a validator that ensures the uploaded file has a valid image extension. |
| default_error_messages | dict = {"invalid_image": "Upload a valid image. The file you uploaded was either not an image or a corrupted image."} | A dictionary of error message templates used by the field, including a specific message for files that are not recognized as valid or uncorrupted images. |
Methods
to_python()
@classmethod
def to_python(
data: Any
) - > [UploadedFile](../../core/files/uploadedfile/uploadedfile.md?sid=django_core_files_uploadedfile_uploadedfile)
Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports).
Parameters
| Name | Type | Description |
|---|---|---|
| data | Any | The raw uploaded file data or dictionary containing file content to be validated as an image |
Returns
| Type | Description |
|---|---|
[UploadedFile](../../core/files/uploadedfile/uploadedfile.md?sid=django_core_files_uploadedfile_uploadedfile) | The file object annotated with image metadata and MIME type, or None if no data was provided |
widget_attrs()
@classmethod
def widget_attrs(
widget: [Widget](../widgets/widget.md?sid=django_forms_widgets_widget)
) - > dict
Extends the default widget attributes to include an 'accept' attribute for image MIME types.
Parameters
| Name | Type | Description |
|---|---|---|
| widget | [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) | The form widget instance for which attributes are being generated |
Returns
| Type | Description |
|---|---|
dict | A dictionary of HTML attributes to be applied to the form widget |