{% extends "model-scope.html" %} {% load static sekizai_tags djng_tags tutorial_tags %} {% block addtoblock %} {{ block.super }} {% addtoblock "css" %}{% endaddtoblock %} {% addtoblock "js" %}{% endaddtoblock %} {% addtoblock "js" %}{% endaddtoblock %} {% add_data "ng-requires" "djng.fileupload" %} {% addtoblock "js" %}{% endaddtoblock %} {% add_data "ng-requires" "djng.urls" %} {% 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 }}" djng-endpoint="." ng-model-options="{allowInvalid: true}" novalidate{% endblock %} {% block form_submission %}{% endblock %} {% block form_foot %} {% verbatim %}
subscribe_data = {{ subscribe_data | json }}{% endverbatim %} {% endblock form_foot %} {% 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 into 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 that reference to the temporary file
will be 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 django.models.ImageField
and/or django.models.FileField
. From this model, you can create a form inheriting from
django.forms.ModelForm
, as usual. Image and file fields then are replaced by their
AngularJS enabled counterparts, enabling drag & drop and immediate image preview.
A sample implementation is shown in the last tab labeled Model.