Search code examples
pythondjangopython-3.xdjango-1.7

ImageField doesnt work


When i try to upload file it gives me template error, that its required to fill in. Code: models:

class ahoja(models.Model):
    image = models.ImageField(upload_to='smayat')

forms:

class ahojaForm(ModelForm):
    class Meta:
        model = ahoja
        exclude = ()

view:

def testview(request):
    if request.method == 'POST': # pokud form byl odeslan
        form = ahojaForm(request.POST, request.FILES) # formular s daty
        if form.is_valid(): 
            form.save() #vytvoří událost
            return HttpResponseRedirect('/hlavni_stranka/kalendar/') 
    else:
        form = ahojaForm() # prázdný formulář
    return render(request, 'hlavni_stranka/test.html', {'form': form,})

Solution

  • The first thing to check is the enctype attribute in your template. From the docs:

    Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.