| 1 | Work in progress |
| 2 | |
| 3 | {{{ |
| 4 | |
| 5 | # models.py |
| 6 | |
| 7 | class SomeFile(models.Model): |
| 8 | description = models.CharField(maxlength=255) |
| 9 | file = models.FileField(upload_to='files') |
| 10 | |
| 11 | }}} |
| 12 | |
| 13 | {{{ |
| 14 | |
| 15 | # manipulators.py |
| 16 | |
| 17 | from models import SomeFile |
| 18 | from django import forms |
| 19 | |
| 20 | class AddFileManipulator(forms.Manipulator): |
| 21 | def __init__(self): |
| 22 | self.fields = ( |
| 23 | forms.TextField(field_name="description", length=30, maxlength=200, is_required=True), |
| 24 | forms.FileField(field_name="file", is_required=True) |
| 25 | ) |
| 26 | |
| 27 | }}} |
| 28 | |
| 29 | |
| 30 | {{{ |
| 31 | |
| 32 | # views.py |
| 33 | |
| 34 | from manipulators import |
| 35 | |
| 36 | def upload_file(request): |
| 37 | manipulator = AddFileManipulator() |
| 38 | |
| 39 | if request.method == 'POST': |
| 40 | # If data was POSTed, we're trying to create a new Place. |
| 41 | new_data = request.POST.copy() |
| 42 | |
| 43 | # Check for errors. |
| 44 | errors = manipulator.get_validation_errors(new_data) |
| 45 | |
| 46 | if not errors: |
| 47 | # No errors. This means we can save the data! |
| 48 | manipulator.do_html2python(new_data) |
| 49 | new_place = manipulator.save(new_data) |
| 50 | |
| 51 | # Redirect to the object's "edit" page. Always use a redirect |
| 52 | # after POST data, so that reloads don't accidently create |
| 53 | # duplicate entires, and so users don't see the confusing |
| 54 | # "Repost POST data?" alert box in their browsers. |
| 55 | return HttpResponseRedirect("/places/edit/%i/" % new_place.id) |
| 56 | else: |
| 57 | # No POST, so we want a brand new form without any data or errors. |
| 58 | errors = new_data = {} |
| 59 | |
| 60 | # Create the FormWrapper, template, context, response. |
| 61 | form = forms.FormWrapper(manipulator, new_data, errors) |
| 62 | return render_to_response('add_file.html', {'form': form}) |
| 63 | |
| 64 | }}} |