首页 > 代码库 > Django ImageField 上传图片并保存到数据库

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

 

转自:http://logic0.blog.163.com/blog/static/188928146201371235435974/

 

Form代码:

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"> 这样才能传图片的撒!

View 示例代码,只适用于 ajax 方式,重要的是里边处理 ImageField 的方式:

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