How it works...

If the JavaScript fails to execute, then the form remains completely usable, but when the JavaScript runs properly, we get an enhanced form with the file field replaced by a simple button, as shown here:

When an image is selected by clicking on the Upload File… button, the result in the browser will look similar to the following screenshot:

Clicking on the Upload File… the button triggers a file dialog that asks you to select a file, and, upon selection, it immediately starts the Ajax upload process. Then we see a preview of the image that has been attached. The preview picture is uploaded to a temporary directory and its filename is saved at the picture_path hidden field. When you submit the form, the form either saves the picture from this temporary location or from the picture field. The picture field will have a value if the form was submitted without JavaScript or if it failed to load the JavaScript. If there are any validation errors for the other fields after the page reload, then the preview image loaded is based on the picture_path.

Let's run through the steps to dig deeper into the process and see how it works.

In our model form for the Location model, we made the picture field nonrequired, although it is required at the model level. In addition, we added the picture_path field there, and then we expect either of those fields to be submitted to the form. In the crispy-forms layout, we defined a custom template for the picture field, file_upload_field.html. There, we set a preview image, upload progress bar, and custom help text with the allowed file formats and minimal dimensions. In the same template, we also attached the CSS and JavaScript files from the jQuery File Upload library and a custom script, picture_upload.js. The CSS files rendered the file upload field as a nice button. The JavaScript files are responsible for the Ajax-based file upload.

The picture_upload.js sent the selected file to the upload_file view. This view checked whether the file is of an image type and then tries to save it under the temporary-uploads/ directory under the project's MEDIA_ROOT. The view returned a JSON with the details about a successful or unsuccessful file upload.

After a picture has been selected and uploaded and the form submitted, the save() method of LocationForm will be called. If the picture_path field value exists, a file will be taken from the temporary directory and copied to the picture field of the Location model. Then the picture at the temporary directory gets deleted and the Location instance is saved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.233.43