Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelForm Imagefield Upload

Tags:

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!

like image 238
Wei Xu Avatar asked Oct 28 '13 07:10

Wei Xu


People also ask

How do I style an ImageField in Django?

from django import forms class ImageForm(forms. Form): image = forms. ImageField( widget = forms. FileInput( attrs = {"id" : "image_field" , # you can access your image field with this id for css styling . , style = "height: 100px ; width : 100px ; " # add style from here . } ) ....


1 Answers

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.

like image 183
Wei Xu Avatar answered Sep 20 '22 15:09

Wei Xu