programmingIsFun
programmingIsFun

Reputation: 1067

Form not valid in django

Hi I am learning Django for a project and I am trying to upload a file along with a on option in dropdown list through a form using POST. Here are my files:

views.py

from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse

from .forms import UploadFileForm

# function to handle an uploaded file.
from save_uploaded_file import handle_uploaded_file


def index(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return render(request, 'viewer_app/display_image.html')
        else:
            print('error')
            return render(request, 'viewer_app/index.html', {'form': form})
    else:
        return render(request, 'viewer_app/index.html')

forms.py

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()
    displayType = forms.ChoiceField(widget=forms.Select(), required=True)

save_uploaded_file.py

def handle_uploaded_file(f):
    with open('static/viewer_app/temp.exr', 'wb+') as recieved_exr:
        for chunk in f.chunks():
            recieved_exr.write(chunk)

index.html

<div id="formDiv" style="display:none;" class="form" >

    <form  method="post" enctype="multipart/form-data" class="form-style">

        <label for="browse">Upload file</label>
        <input type="file" value="Browse" id="brow" /><br></br>

        <label for="display">Display type</label>
        <select id="display-type" name="display">
            <option id="RGB1" value="RGB1">RGB1</option>
            <option id="RGB2" value="RGB2">RGB2</option>
            <option id="RGB3" value="RGB3">RGB3</option>
            <option id="RGB4" value="RGB4">RGB4</option>
        </select><br></br>

        <input type="submit" value="Show file" id="showimage"/><br></br>
        {% csrf_token %}        

    </form>
</div>

So, after I run the server to display the page and I select the upload and click submit, it doesn't upload and save the file and in the terminal I see the "error" text in the terminal which is displayed due to from.is_valid() not being true.

I tried to add {{ form.errors }} {{ form.non_field_errors }} to the html file but I still don't know exactly what is that I am doing wrong.

Upvotes: 1

Views: 2398

Answers (1)

Shivam Sharma
Shivam Sharma

Reputation: 919

Also I can see the absence of name attributes inside your <input> tag and a potentially wrong name attribute inside your <select> tag. You should put the exact name of the field inside your html 's name attribute for the form to get bounded. Same goes for the <select> tags.

Try putting:

<input type="file" value="Browse" id="brow" name="file"/>

and

<select id="display-type" name="displayType">

and probably your problem will be solved. If I may suggest, why aren't you using the standard django template form tags, Such as {{ form.as_p }} ? These methods are quite handy and will also handle the errors successfully. You should try using them. check them here

EDIT You haven't given any choices attribute to you ChoiceField in your forms.py. Make sure to give a attribute choices as a tuple to your ChoiceField. It can be done as:

#import ugettext_lazy
from django.utils.translation import ugettext_lazy as _

#inside your form class
class UploadFileForm(forms.Form):
    CHOICES = (
        ('RGB1', _('RGB1')),
        ('RGB2', _('RGB2')),
        ('RGB3', _('RGB3')),
        #And so on
    )
    #First option in the tuple is stored in db. Second is displayed in Forms.
    displayType = forms.ChoiceField(widget=forms.Select(), required=True , choices = CHOICES)
    file = forms.FileField()

EDIT 2:

Get the file url as below,

from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('viewer_app/temp.exr')
#See if temp.exr exists prior to this. Otherwise create a file manually  or through python.

Then open the file by supplying this url.

Again I would recommend you to check ModelForms. They'll completely eliminate the need to write files this way.

Hope it helps. Thanks.

Upvotes: 1

Related Questions