Code

Ticket #1653: forms.txt.3.diff

File forms.txt.3.diff, 2.2 KB (added by asmodai@…, 8 years ago)

2nd update, fixes a typo and rewords part of a sentence

Line 
1Index: docs/forms.txt
2===================================================================
3--- docs/forms.txt      (revision 3131)
4+++ docs/forms.txt      (working copy)
5@@ -581,6 +581,51 @@
6     the executable specified in the ``JING_PATH`` setting (see the settings_
7     document for more details).
8 
9+FileField, ImageField and forms
10+===============================
11+
12+Where most, if not all, model fields only require a simple addition in the
13+form of ``{{ form.fieldname }}`` to a template, the situation is a bit
14+different for the FileField and ImageField fields.
15+
16+Say that in the model definition there is a declaration for::
17+
18+    file = model.FileField('/path/to/upload/location')
19+
20+Normally this would be used in a template form like the following::
21+
22+    <p><label for="file">File:</label> {{ form.file }}</p>
23+
24+The first thing that is noticeable when the page is opened in a browser is
25+that there is no typical text field with a browse button, as would be
26+expected.
27+
28+To get this behaviour a little change to the template is needed to get the
29+following::
30+
31+    <p><label for="file">File:</label> {{ form.file }}{{ form.file_file }}</p>
32+
33+If you would reload the page it should now show a file upload text field
34+complete with a browse button.
35+
36+The HTML standard specifies the ``enctype`` attribute to the ``form`` element
37+in order to select the content type used in submitting. The default is
38+``application/x-www-form-urlencoded``, the format that uses ampersands in the
39+URL to separate key-value pairs next to some other encoding tricks. This is
40+the wrong encoding type to use when working with forms that will use file
41+uploads. The ``form`` element must get an ``enctype`` attribute with its value
42+set to ``multipart/form-data``.
43+
44+Also make sure to use ``form.file_file`` with validation and not
45+``form.file``.
46+
47+In the view make sure that the ``update(request.FILES)`` method is called
48+after the object has been created with the ``request.POST.copy()`` call, as
49+such::
50+
51+    new_data = request.POST.copy()
52+    new_data.update(request.FILES)
53+
54 .. _`generic views`: http://www.djangoproject.com/documentation/generic_views/
55 .. _`models API`: http://www.djangoproject.com/documentation/model_api/
56 .. _settings: http://www.djangoproject.com/documentation/settings/