Django ModelForm Imagefield上传

时间:2013-10-28 07:14:31

标签: python django modelform

我是Django的新手,我在使用ModelForm处理图像上传时遇到了问题。 我的模型如下:

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)

模型形式如下:

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

View功能是:

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})

模板是:

<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>

任何人都可以帮助我,还是可以举例说明图片上传? 谢谢!

2 个答案:

答案 0 :(得分:47)

好的,谢谢大家。我发现自己犯了一个愚蠢的错误。 我应该在enctype="multipart/form-data"中添加<form> 否则,它不会上传文件。

答案 1 :(得分:2)

您不需要将newproject.photo设置为request.FILES['photo'](实际上这可能会破坏您的代码)。只需使用addprojectform代替addprojectform.save()保存newproject = addprojectform.save(commit=False)。在此处查看更多信息:https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/#handling-uploaded-files-with-a-model