Search code examples
djangodjango-formsdjango-file-upload

modelForm giving a validation error on file upload


I'm trying to do a bare bones files upload, but there seems to be a problem while validating the model form.

Here's my model:

class quiz(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200)
    questions_file = models.FileField(upload_to=get_path)
    end_date = models.DateField()
    time = models.IntegerField()


    def __unicode__(self):
        return self.name

My forms.py

class quizForm(ModelForm):
class Meta:
    model = quiz
    fields = ['title','questions_file','end_date','time']

Relevant View:

def upload(request):
    if request.user.is_authenticated():     
        if request.method == 'POST':
                form = quizForm(request.POST,request.FILES)
                if form.is_valid():
                    quiz = form.save(commit=False)
                    quiz.user = request.user
                    quiz.save()
                else:
                    return HttpResponse(form.errors)
        else:
            form = quizForm()
            return render_to_response('upload.html',{'form':form},context_instance=RequestContext(request))
    else:
        return HttpResponse('Not logged in')

Template :

<form enctype="multi-part/form-data" action='/test-upload/' method='POST'>
{% csrf_token %}
{{form.as_p}}
<input type='submit' name='submit'>
</form>

on submitting a file through the form. I'm getting a http response of questions_file i.e. t he file is not properly being validated.

Thanks in advance. Also please ignore indentations error, Im a noob in SO formatting.


Solution

  • Typo within the form encoding type:

    <form enctype="multipart/form-data" action='/test-upload/' method='POST'>
        {% csrf_token %}
        {{form.as_p}}
        <input type='submit' name='submit'>
    </form>