un1t / django-file-resubmit

It remembers selected files in form on validation errors.
76 stars 39 forks source link

Document how to access the uploaded file #18

Open mnelson4 opened 7 years ago

mnelson4 commented 7 years ago

I'm using this with Django 1.10 and this works fine. I would suggest maybe adding a bit to the documentation on how to access the submitted-or-cached file on form fields. Wth a normal field, this code worked fine:

forms.py
====================
class DocForm(ModelForm):
    reason = CharField()
    attachment = FileField(required=False,widget=ResubmitFileWidget())
    class Meta:
        model = Doc
        include = ('reason', 'attachment')
views.py (only works if files in request, not if they're in the cache)
====================
def receive_submission(request):
    if request.method == 'POST':
        form = DocForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['attachment']
            filename = file.name
            file_content = file.read()
            ...

But that doesn't work with files fields that are automatically resubmitted (ie, the first time the form was submitted there was some other validation error, but the 2nd time the form was submitted that validation error was fixed, but the file wasn't re-selected in the form, so we are relying on the cache to provide the file's info). And once you figure out the internals of this module, it makes sense why that doesn't work. But it would be nice if the readme would just show the proper way to access the uploaded file (whether it's contained request.FILES or from the cache). I.e., you need to use code like this:

views.py (works if files in request or cache)
=====================
def receive_submission(request):
    if request.method == 'POST':
        form = DocForm(request.POST, request.FILES)
        if form.is_valid():
            file = form.cleaned_data['attachment']
            filename = file.name
            file_content = file.read()
            ...