Django ImageField 上传图片并保存到数据库

From 代码

 

class ImageUploadForm(forms.Form):
    """Image upload form."""
    image = forms.ImageField()

 

Model 代码

class ExampleModel(models.Model):
    model_pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/no-img.jpg')

对应的模板代码

   <form action="{% url upload_pic %}" method="post" enctype="multipart/form-data">{% csrf_token %}
                <p>
                      <input id="id_image" type="file" class="" name="image"> <!-- 这一行应该是form.image,省事写的 -->
                </p>
                <input type="submit" value="Submit" />
          </form>

注意: :<form ... enctype="multipart/form-data"> 这样才能传图片的撒!

 

def upload_pic(request):
      if request.method == 'POST':
          form = ImageUploadForm( request.POST, request.FILES )  # 有文件上传要传如两个字段
          if form.is_valid():
              m = ExampleModel.objects.get(pk=course_id)
              m.model_pic = form.cleaned_data['image']                     # 直接在这里使用 字段名获取即可
              m.save()
              return HttpResponse('image upload success')
      return HttpResponseForbidden('allowed only via POST')

 

posted @ 2017-02-14 12:57  邹文强  阅读(692)  评论(0编辑  收藏  举报