Index: docs/forms.txt =================================================================== --- docs/forms.txt (revision 3131) +++ docs/forms.txt (working copy) @@ -581,6 +581,51 @@ the executable specified in the ``JING_PATH`` setting (see the settings_ document for more details). +FileField, ImageField and forms +=============================== + +Where most, if not all, model fields only require a simple addition in the +form of ``{{ form.fieldname }}`` to a template, the situation is a bit +different for the FileField and ImageField fields. + +Say that in the model definition there is a declaration for:: + + file = model.FileField('/path/to/upload/location') + +Normally this would be used in a template form like the following:: + +
{{ form.file }}
+ +The first thing that is noticeable when the page is opened in a browser is +that there is no typical text field with a browse button, as would be +expected. + +To get this behaviour a little change to the template is needed to get the +following:: + +{{ form.file }}{{ form.file_file }}
+ +If you would reload the page it should now show a file upload text field +complete with a browse button. + +The HTML standard specifies the ``enctype`` attribute to the ``form`` element +in order to select the content type used in submitting. The default is +``application/x-www-form-urlencoded``, the format that uses ampersands in the +URL to separate key-value pairs as well as some other encoding tricks. This +the wrong encoding type to use when working with forms that will use file +uploads. The ``form`` element must get an ``enctype`` attribute with its value +set to ``multipart/form-data``. + +Also make sure to use ``form.file_file`` with validation and not +``form.file``. + +In the view make sure that the ``update(request.FILES)`` method is called +after the object has been created with the ``request.POST.copy()`` call, as +such:: + + new_data = request.POST.copy() + new_data.update(request.FILES) + .. _`generic views`: http://www.djangoproject.com/documentation/generic_views/ .. _`models API`: http://www.djangoproject.com/documentation/model_api/ .. _settings: http://www.djangoproject.com/documentation/settings/