{% extends "subscribe-form.html" %} {% load static sekizai_tags djng_tags tutorial_tags %} {% block addtoblock %} {{ block.super }} {% addtoblock "css" %}{% endaddtoblock %} {% addtoblock "js" %}{% endaddtoblock %} {% addtoblock "js" %}{% endaddtoblock %} {% addtoblock "ng-requires" %}djng.fileupload{% endaddtoblock %} {% addtoblock "js" %}{% endaddtoblock %} {% addtoblock "ng-requires" %}djng.urls{% endaddtoblock %} {% addtoblock "ng-config" %}['$httpProvider', function($httpProvider) { $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['X-CSRFToken'] = '{{ csrf_token }}'; }]{% endaddtoblock %} {% endblock addtoblock %} {% block main-intro %}
New in 1.1 Drag and drop images or files into a form
This example shows how to upload an image or file to the server using AngularJS with Ajax.
{% endblock main-intro %} {% block form_tag %}name="{{ form.form_name }}" method="post" action="." validate ng-controller="MyFormCtrl"{% endblock %} {% block form_submission %} {% endblock %} {% block form_foot %} {% verbatim %}MyFormCtrl
's scope:subscribe_data = {{ subscribe_data | json }}{% endverbatim %} {% endblock form_foot %} {% block demo_scripts %} {{ block.super }} {% endblock %} {% block main-tutorial %}
If we want to upload an image or file to the server through an Ajax request, we have to divide
the submission in two steps. This is because browsers can not serialize submitted file payload to
JSON. Instead, we first must upload the image or file to the server encoded as
multipart/form-data
. The server then creates a temporary copy of the uploaded image
or file and returns a reference to it. This temporary reference is stored inside a hidden field
of our form.
When the complete form is submitted by the client, only the reference to the temporary file is
sent through Ajax. The server then moves the previously uploaded copy of that file into its
MEDIA_ROOT
directory and stores its location inside a model field.
A form accepting files and images without a permanent storage does not make
much sense. Therefore you normally would create a Django model using an models.ImageField
and/or models.FileField
. From this model, you can create a form as usual. Image and
file fields then are replaced by their AngularJS enabled counterparts, enabling drag & drop and
immediate image preview.
Some example code is shown in the last tab labeled Model.