Home  >  Article  >  Backend Development  >  Django project practical user avatar upload and access

Django project practical user avatar upload and access

不言
不言Original
2018-04-21 14:49:062236browse

This article mainly introduces the practical examples of uploading and accessing user avatars in Django projects. Now I share them with you and give them a reference. Let’s take a look together

1 Save the file locally on the server

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <p>用户名:<input type="text" name="username"></p>
  <p>头像<input type="file" name="avatar"></p>
  <input type="submit" value="提交">
</form>
</body>
</html>

urls.py

from django.conf.urls import url
from app01 import views
urlpatterns = [
  url(r&#39;^upload&#39;,views.upload)
]

views.py

from django.shortcuts import render,HttpResponse 
def upload(request):
  if request.method == &#39;POST&#39;:
    name = request.POST.get(&#39;username&#39;)
    avatar = request.FILES.get(&#39;avatar&#39;)
    with open(avatar.name,&#39;wb&#39;) as f:
      for line in avatar:
        f.write(line)
    return HttpResponse(&#39;ok&#39;)
  return render(request,&#39;upload.html&#39;)

Summary

In this way, we have made a basic small example of file upload. There are a few points to note here:
1. The form requires Add csrf_token verification
2. The type value of the input box of the file is file
3. To obtain the file in the view function, use the request.FILES.get() method
4. Through obj.name Get the name of the file

2 Upload the file to the database

models.py

from django.db import models
 class User(models.Model):
  username = models.CharField(max_length=16)
  avatar = models.FileField(upload_to=&#39;avatar&#39;)

views.py

def upload(request):
  if request.method == &#39;POST&#39;:
    name = request.POST.get(&#39;username&#39;)
    avatar = request.FILES.get(&#39;avatar&#39;)
    models.User.objects.create(username=name,avatar=avatar)
    return HttpResponse(&#39;ok&#39;) 
  return render(request,&#39;upload.html&#39;)

Summary

The function of uploading files to the database has been implemented above. There are a few points to note:
1. The so-called uploading to the database does not mean placing the image itself or the binary code in the database. It actually uploads the file to the server locally. The database only stores the path of a file, so that when the user wants to call the file, he can go to the location specified by the server through the path.
2. When creating the ORM, the avatar field must have an upload_to='' attribute, specify Where to put the uploaded files
3. When adding to the database, the file field attribute assignment is the same as the ordinary field in form, such as: models.User.objects.create(username=name,avatar=avatar)
4. If there are duplicate file names uploaded by two users, the system will automatically rename the file, with the following effect:

##Append

We have implemented the function. It seems that when we call the file, we only need to access the image through the file itself that has been saved in the database file path and let it appear on the web page. In fact, it does not That's not the case.


We need to configure something so that django can find it, otherwise it will fail the urls verification. The reason why we can directly access the static files in static is because django It has been configured for us.


The configuration steps are as follows:


1. Configure


in the site’s setting.py

MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media") #blog是项目名,media是约定成俗的文件夹名

MEDIA_URL="/media/"   # 跟STATIC_URL类似,指定用户可以通过这个路径找到文件

2. Configure in urls.py


from django.views.static import serve
from upload import settings        #upload是站点名
url(r&#39;^media/(?P<path>.*)$&#39;, serve, {&#39;document_root&#39;: settings.MEDIA_ROOT}),

After configuring, you can pass http://127.0.0.1:8001/media/milk.png accessed the picture


3 Use AJAX to submit the file

upload. html


<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
<form>
  {% csrf_token %}
  <p>用户名:<input id="name-input" type="text"></p>

  <p>头像<input id="avatar-input" type="file"></p>
  <input id="submit-btn" type="button" value="提交">
</form>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
  $(&#39;#submit-btn&#39;).on(&#39;click&#39;,function () {
    formdata = new FormData();
    formdata.append(&#39;username&#39;,$(&#39;#name-input&#39;).val());
    formdata.append("avatar",$("#avatar")[0].files[0]);
    formdata.append("csrfmiddlewaretoken",$("[name=&#39;csrfmiddlewaretoken&#39;]").val()); 
 $.ajax({
 processData:false,contentType:false,url:&#39;/upload&#39;, type:&#39;post&#39;, data:formdata,success:function (arg)
 { 
if (arg.state == 1){ alert(&#39;成功!&#39;) }
else { alert(&#39;失败!&#39;) } } }) });
 </script>
 </body> 
</html>

views.py


from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from app01 import models
def upload(request):
  if request.method == &#39;POST&#39;:
    name = request.POST.get(&#39;username&#39;)
    avatar = request.FILES.get(&#39;avatar&#39;)
    try:
      models.User.objects.create(username=name,avatar=avatar)
      data = {&#39;state&#39;:1}
    except:
      data = {&#39;state&#39;:0}
    return JsonResponse(data)
  return render(request,&#39;upload.html&#39;)

Summary


1. When Ajax uploads, the button type must not use submit

2. When Ajax uploads, the value of the data parameter is no longer an ordinary 'dictionary' type value, but a FormData object

  1. Create the object formdata = new FormData();

  2. Add the value formdata.append('username',$( '#name-input').val());

3.Ajax must add csrf verification when submitting a post

  1. formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());

4. Finally, when uploading files via Ajax, there must be Two parameter settings

  1. processData:false

  2. contentType:false

4 There is a preview function when uploading image files

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
<form>
  <!----用一个label标签将上传文件输入框跟图片绑定一起,
     点击图片的时候就相当于点击了上传文件的按钮---->
  <label><img id="avatar-img" src="/static/img/default.png" width="80px" height="80px">
    <p>头像<input id="avatar-input" hidden type="file"></p>

  </label>
  <input id="submit-btn" type="button" value="提交">
</form>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
  // 上传文件按钮(label里的图片)点击事件
  $(&#39;#avatar-input&#39;).on(&#39;change&#39;,function () {
    // 获取用户最后一次选择的图片
    var choose_file=$(this)[0].files[0];
    // 创建一个新的FileReader对象,用来读取文件信息
    var reader=new FileReader();
    // 读取用户上传的图片的路径
    reader.readAsDataURL(choose_file);
    // 读取完毕之后,将图片的src属性修改成用户上传的图片的本地路径
    reader.onload=function () {
       $("#avatar-img").attr("src",reader.result)
    }
  });
</script>

##5 Summary


For file upload, whether it is direct form submission or Ajax submission, the fundamental problem is to tell the browser that what you want to upload is a file instead of an ordinary string


What about We tell the browser by requesting the ContentType parameter of the weight. We don’t need to specify it when uploading a normal string, because it has a default value,


. And if you want to upload a file, you need to specify it separately. . Summarize the following points

1. For form upload, ContentType is specified through enctype="multipart/form-data"

2. For ajax upload, ContentType is specified through processData:false and contentType:false
3. When the form is uploaded, the file data is "wrapped" through the 3525558f8f338d4ea90ebf22e5cde2bc tag.
4. When the ajax is uploaded, the data is added through a FormData instance object. Just pass this object when passing it
5. After the data is passed, it is encapsulated in request.FILES instead of request.POST


Related recommendations:

How Django loads css and js files and static images

Detailed explanation of the use of django controls and parameter passing

The above is the detailed content of Django project practical user avatar upload and access. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn