Thursday, June 5, 2014

Re: Displaying an uploaded file in a form

On Thu, Jun 5, 2014 at 8:12 PM, Shawn H <shawn.holyoak@gmail.com> wrote:
> I've been trying to understand how to handle file uploads, and I've got the
> upload portion down. I have a FileField in my form, process it in my view,
> and it's saved in the correct location as specified in MEDIA_ROOT and the
> upload_to attribute of the Model. My problem is, when I try to bind the
> uploaded document in a GET request, nothing is working. I tried following
> the documentation in the docs, but when I do that I get a 'FieldFile' does
> not have the buffer interface error. How do I bind the file to the form so
> it's available to the user to download or open, while preserving the ability
> for the user to replace the uploaded file? Do I have to extract the file
> from the model field before binding it to the form? Code below. Thanks in
> advance
>
> form_data = {
> 'sub_id':s.id,
> ...
> 'sub_verified_by':s.verified_by
> }
> form_file = {'sub_pdr': SimpleUploadedFile('SubmissionPDR.docx',
> s.pdr_file)}
> form = SubmissionEditForm(form_data, form_file)

I think you are trying to redisplay a form that has already been
submitted, with the file there? This is not going to work, mainly
because a file field in a form never has an initial value, but also
because it is the wrong approach.

To display all the fields apart from the file field, you should be
passing the form data to the form as initial, not as data - eg
SubmissionEditForm(initial=form_data) - so that you do not create a
bound form - a form that has been submitted already.

To make the file available to download, you simply add the url to the
file to your template context - s.pdr_file.url - and make a link to it
- no forms involved. Or just add 's', and access it in the template:

{% if s.pdr_file %}
<a href="{{ s.pdr_file.url }}">Download file</a>
{% endif %}

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BtVerhqeSDJbyahUVwp68ojzS2atB8tdW%2B0%2BqBPhRHAg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment