User avatar upload and access for Django Project combat

Source: Internet
Author: User

1 Save the file to the server local upload.html
<! DOCTYPE html>
urls.py
From django.conf.urls import urlfrom app01 Import viewsurlpatterns = [    url (R ' ^upload ', views.upload)]
views.py
From django.shortcuts import render,httpresponsedef upload (Request):    if Request.method = = ' POST ':        name = Request. Post.get (' username ')        avatar = Request. Files.get (' Avatar ')        with open (Avatar.name, ' WB ') as F: For line in            Avatar:                f.write (line)        return HttpResponse (' OK ')    return render (Request, ' upload.html ')
Summarize

In this way, we have done a basic file upload small example, here are a few things to note:

    1. Need to add Csrf_token validation to form forms
    2. The value of the type of the file's input box is file
    3. To get a file in a view function, use request. Files.get () method
    4. The name of the file can be obtained by obj.name
2 uploading files to the database models.py
From django.db import Modelsclass User (models. Model):    username = models. Charfield (max_length=16)    avatar = models. Filefield (upload_to= ' Avatar ')
views.py
def upload (Request):    if Request.method = = ' POST ':        name = Request. Post.get (' username ')        avatar = Request. Files.get (' Avatar ')        models. User.objects.create (Username=name,avatar=avatar)        return HttpResponse (' OK ')    return render (Request, ' Upload.html ')
Summarize

The above has implemented the ability to upload files to the database, there are several points to note:

    1. The so-called upload to the database, not to tell the picture itself or binary stacking in the database, and actually upload the file to the server locally, the database is just a path to save a file, so that the user can call the file by the path to the server designated location to find
    2. When creating an ORM, the Avatar field must have a property of upload_to= ', specifying where the uploaded file is placed
    3. When adding to the database, the File field property assignment is the same as the normal field, such as: models. User.objects.create (Username=name,avatar=avatar)
    4. If two users upload a duplicate file name, the system will automatically rename the files, the effect is as follows:

Additional

Function We are implemented, it seems that when we call the file, only through the database file path has been saved by the file itself can access the picture, let it appear on the Web page, in fact, it is not so,

We need to configure something, Django can find it, otherwise it will not be able to get through the URLs verification, and we can directly access static files in static, because Django has been configured for us.

The configuration steps are as follows:

1, in the site of the setting.py configuration

Media_root=os.path.join (Base_dir, "blog", "Media")  #blog是项目名, Media is the agreed idiomatic folder name media_url= "/media/"      # with Static Similar to _url, the specified user can find the file through this path

2, in the urls.py configuration

From django.views.static import servefrom upload import Settings                #upload是站点名url (R ' ^media/(? p<path>.*) $ ', serve, {' Document_root ': Settings. Media_root}),
Once configured, you will be able to access the image via Http://127.0.0.1:8001/media/milk.png.

3 Submitting files with Ajax upload.html
<! DOCTYPE html> 
Formdata.append ("Avatar", $ ("#avatar") [0].files[0]);
       
$.ajax ({
Processdata:false,





if (arg.state = = 1) {alert (' Success! ')}else {alert (' failed! ‘) } } }) });
</script> </body>
views.py
From django.shortcuts import render,httpresponsefrom django.http import jsonresponsefrom app01 import modelsdef upload ( Request):    if Request.method = = ' POST ':        name = Request. Post.get (' username ')        avatar = Request. Files.get (' Avatar ')        try:            models. User.objects.create (username=name,avatar=avatar)            data = {' state ': 1}        except:            data = {' state ': 0}        return Jsonresponse (data)    return render (Request, ' upload.html ')
Summarize
    1. Ajax upload, the button Tpye must not use the Submit
    2. When Ajax uploads, the value of the data parameter is no longer a normal ' dictionary ' type value, but a formdata
      • Create Object FormData = new FormData ();
      • Add the value formdata.append (' username ', $ (' #name-input ') to the inside. Val ());
    3. Ajax to add CSRF verification when doing post submission
      • Formdata.append ("Csrfmiddlewaretoken", $ ("[name= ' Csrfmiddlewaretoken ']"). Val ());
    4. Finally, Ajax uploads a file with two parameter settings
      • Processdata:false
      • Contenttype:false
4 Preview function when uploading image files
<! DOCTYPE html>5 Big summaries

For file upload, whether it is a direct form submission or AJAX submissions, the fundamental problem is to tell the browser that you want to upload a file instead of a normal string

And how to tell the browser, that is, by asking for the weight of the contenttype parameter, we upload the normal string without specifying, because it has a default value,

And if you want to pass the file, you have to specify it separately. Summarize the following points

    1. The form forms are uploaded by enctype= "Multipart/form-data" to specify ContentType
    2. Ajax uploads are specified by processdata:false and Contenttype:false ContentType
    3. When the form is uploaded, the file data is "wrapped" by <input type= "file" > tag.
    4. When Ajax uploads, the data is added via an FormData instance object, which is passed when the object is passed.
    5. After the data is passed through, it is encapsulated in the request. Files , not request. In post

User avatar upload and access for Django Project combat

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.