Django ModelForm Imagefield Upload

Wei Xu picture Wei Xu · Oct 28, 2013 · Viewed 19k times · Source

I am pretty new to Django and I met a problem in handling image upload using ModelForm. My model is as following:

class Project(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=2000)
    startDate = models.DateField(auto_now_add=True)
    photo = models.ImageField(upload_to="projectimg/", null=True, blank=True)

And the modelform is as following:

class AddProjectForm(ModelForm):
    class Meta:
        model = Project
        widgets = {
            'description': Textarea(attrs={'cols': 80, 'rows': 50}),
        }
        fields = ['name', 'description', 'photo']

And the View function is:

def addProject(request, template_name):
if request.method == 'POST':
    addprojectform = AddProjectForm(request.POST,request.FILES)
    print addprojectform
    if addprojectform.is_valid():
        newproject = addprojectform.save(commit=False)
        print newproject
        print request.FILES
        newproject.photo = request.FILES['photo']
        newproject.save()
        print newproject.photo
else:
    addprojectform = AddProjectForm()

newProposalNum = projectProposal.objects.filter(solved=False).count()
return render(request, template_name, {'addprojectform':addprojectform,
                                       'newProposalNum':newProposalNum})

the template is:

<form class="bs-example form-horizontal" method="post" action="">{% csrf_token %}
                      <h2>Project Name</h2><br>
                      {{ addprojectform.name }}<br>
                      <h2>Project Description</h2>
                      {{ addprojectform.description }}<br>
                      <h2>Image Upload</h2><br>
                      {{ addprojectform.photo }}<br>
                      <input type="submit" class="btn btn-success" value="Add Project">
                  </form>

Can anyone help me or could you give an example of image uploading? Thank you!

Answer

Wei Xu picture Wei Xu · Oct 28, 2013

OK, thanks everyone. I found myself made a stupid mistake. I should add enctype="multipart/form-data" in the <form> Else, it won't upload the file.