Django ModelForm Imagefield Upload
Posted
by
Wei Xu
on Stack Overflow
See other posts from Stack Overflow
or by Wei Xu
Published on 2013-10-28T07:14:31Z
Indexed on
2013/10/28
15:54 UTC
Read the original article
Hit count: 192
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!
© Stack Overflow or respective owner