Django ImageField 上傳圖片並保存到數據庫

 

轉自:http://logic0.blog.163.com/blog/static/188928146201371235435974/ajax

 

Form代碼:post

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

Model 代碼:url

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

對應的 模版 代碼spa

 <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"> 這樣才能傳圖片的撒!code

View 示例代碼,只適用於 ajax 方式,重要的是裏邊處理 ImageField 的方式:orm

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') 
相關文章
相關標籤/搜索