Django Upload Images

Source: Internet
Author: User

Django Modified Avatar features ...

1. Add Enctype= "multipart/form-data to the form;

Introduction to Enctype in forms: http://www.w3school.com.cn/tags/att_form_enctype.asp

The view that processes the form accepts data from the upload file in the request. files is a dictionary that contains the keys for each Filefield

(or subclass of Imagefield,filefield). In this case, you can use request. files[' File ' to store the data in the form.  

Note the request. Files is only available when the request method is post and the <form> owning enctype= "Multipart/form-data property of the request is sent.

Data is included. otherwise request. Files is empty

As shown in the following:

Display picture information after submission:

If you do not add enctype= "Multipart/form-data: Cannot get the picture information, only the path

2. Uploading images

Because the photo field in the model stores a path, the first thing to do is to save the picture in the folder that corresponds to the picture.

Save the image to use the PIL library, the picture for a variety of operations----reference: Liaoche--pil;PIL official documents

I use a simple function, just save the picture. Code:

Photo=request. files[' photo '        if Photo:            phototime= request.user.username+str (Time.time ()). Split ('. ') [0]            PHOTO_LAST=STR (photo). Split ('. ') [-1]            Photoname= ' photos/%s.%s '% (phototime,photo_last)

       Img=image.open (photo) Img.save (' media/' +photoname)

3. Update the picture path to the database

Call the update () method.

Note: The update () method is valid for any result set (QuerySet). by The Get () method is not the Queryset,

Therefore, can not update, and the Get () method does not reach the data and the number of return bar is greater than 1 when the error will be.

Print type (UserInfo.objects.get (id=userinfo_id))---> <class ' Account.models.UserInfo ' >print type ( UserInfo.objects.filter (id=userinfo_id))----> <class ' django.db.models.query.QuerySet ' >
The relevant code is as follows:
models.py
Class UserInfo (models. Model):    user=models. Onetoonefield (User)       photo=models. ImageField (upload_to= ' photos ', default= ' user1.jpg ')    def __unicode__ (self):        return Self.user.username

HTML code

<form action= "/updateinfo" method= "POST" enctype= "Multipart/form-data" >            <div class= "Updateimg" >             </div>                                   <input name= "photo" type= "file" id= " Exampleinputfile ">                         <button id=" photo "class=" btn Btn-danger "type=" submit "> Upload avatar </button>

views.py

def updateInfo (Request):    if request.method== ' POST ':        photo=request. files[' photo '        if Photo:            phototime= request.user.username+str (Time.time ()). Split ('. ') [0]            PHOTO_LAST=STR (photo). Split ('. ') [-1]            Photoname= ' photos/%s.%s '% (phototime,photo_last)            img=image.open (photo)            Img.save (' media/' +photoname)            Count=userinfo.objects.filter (user=request.user). Update (                photo=photoname            )            if Count:                # Set a session, and then jump to the corresponding page, where it is easy to write                return HttpResponse (' upload success ')                             else:                return HttpResponse (' upload failed ')        return HttpResponse (' picture is empty ')

  

Reference:http://bluecrystal.iteye.com/blog/233030

   Http://python.usyiyi.cn/django/index.html

   Liaoche--pil

============ If there is a mistake, please correct me. Reprint Please specify the source ==============

  





Django Upload Images

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.