Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

You shouldn't need to set the newproject.photo to request.FILES['photo'] (actually this right here probably breaks your code). Just save the addprojectform with addprojectform.save() instead of newproject = addprojectform.save(commit=False). See more info here: https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/#handling-uploaded-files-with-a-model

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top