4

I have an input tag where the user has to upload a file. Right now if the user doesn't upload anything I do this in the main view:

if len(request.FILES) != 0:

    data = request.FILES['some_file']
    ...do some work...
else:
    return render(request, 'App/nofile.html' )

If there is no file I take the user the another page where it says that no file was uploaded and make him/her go back to the main page.

Is there a way that I can check if the user did not uploaded a file and not go to another page just show a PICTURE in the middle of the screen in that main page with the message?

NOT JUST A STRING MESSAGE, a picture with the message.

Maybe javascript is the answer but I know nothing about javascript.

Thanks in advance for any help.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
NachoMiguel
  • 983
  • 2
  • 15
  • 29
  • 2
    Yes you can show a PICTURE not JUST A STRING MESSAGE by WRITING SOME HTML that uses the IMAGE TAGS to display AN image WHERE you want IT. – Daniel Roseman Sep 16 '15 at 12:30
  • @DanielRoseman ok, i wanted to know how to show that picture in a validation on the django template. Thanks – NachoMiguel Sep 16 '15 at 13:57
  • 1
    @DanielRoseman i know that was unnecesary sarcasm, just wanted to make my point with the uppercases, and you are a pro so you know the answer to this. Just help a non expert – NachoMiguel Sep 16 '15 at 14:53

1 Answers1

6

There are two ways:

1) If you do validation on server side just like you do right now. It seems that you do it right, but you should use redirect instead of render if you handle POST data:

if len(request.FILES) != 0:

    data = request.FILES['some_file']
    ...do some work...
else:
    return redirect('/nofile/' {'foo': bar})

2) If you want client-side validation. Then you must prevent default submit action by javascript and check if file length equals 0. You can check this question or use this jQuery snippet:

$('form').submit(function(event){
    validated = true;

    if ($('#some_file_input').get(0).files.length === 0) {
        validated = false;
        console.log("No files selected.");
        // Or some div with image showing
    }

    if (validated != true) {
        event.preventDefault();
    }
});
valignatev
  • 6,020
  • 8
  • 37
  • 61
  • right now i am not being able to use that javascript code, maybe i am not assignin the input to the function in the correct way. this is my input Your code says: if ($('#some_file_input')----->is this the id? – NachoMiguel Sep 16 '15 at 15:02
  • Figured it out, very helpfull, not like other comments – NachoMiguel Sep 16 '15 at 15:13