Django project practical user avatar upload and access
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'^upload',views.upload) ]
views.py
from django.shortcuts import render,HttpResponse def 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')
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='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')
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
MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media") #blog是项目名,media是约定成俗的文件夹名 MEDIA_URL="/media/" # 跟STATIC_URL类似,指定用户可以通过这个路径找到文件
from django.views.static import serve from upload import settings #upload是站点名 url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
3 Use AJAX to submit the file
<!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> $('#submit-btn').on('click',function () { formdata = new FormData(); formdata.append('username',$('#name-input').val()); formdata.append("avatar",$("#avatar")[0].files[0]); formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()); $.ajax({ processData:false,contentType:false,url:'/upload', type:'post', data:formdata,success:function (arg) { if (arg.state == 1){ alert('成功!') } else { alert('失败!') } } }) }); </script> </body> </html>
from django.shortcuts import render,HttpResponse from django.http import JsonResponse from app01 import models def 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')
2. When Ajax uploads, the value of the data parameter is no longer an ordinary 'dictionary' type value, but a FormData object
- Create the object formdata = new FormData();
- Add the value formdata.append('username',$( '#name-input').val());
- formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());
- processData:false
- 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里的图片)点击事件 $('#avatar-input').on('change',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>
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
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 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the "Discover" button in the lower right corner, and then select the "Notes" option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the "Follow" button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select "Personal Information"

In Ubuntu systems, the root user is usually disabled. To activate the root user, you can use the passwd command to set a password and then use the su- command to log in as root. The root user is a user with unrestricted system administrative rights. He has permissions to access and modify files, user management, software installation and removal, and system configuration changes. There are obvious differences between the root user and ordinary users. The root user has the highest authority and broader control rights in the system. The root user can execute important system commands and edit system files, which ordinary users cannot do. In this guide, I'll explore the Ubuntu root user, how to log in as root, and how it differs from a normal user. Notice

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

After registering a win10 account, many friends feel that their default avatars are not very good-looking. For this reason, they want to change their avatars. Here is a tutorial on how to change their avatars. If you want to know, you can come and take a look. . How to change the win10 account name and avatar: 1. First click on the lower left corner to start. 2. Then click the avatar above in the pop-up menu. 3. After entering, click "Change Account Settings". 4. Then click "Browse" under the avatar. 5. Find the photo you want to use as your avatar and select it. 6. Finally, the modification is completed successfully.

Analysis of user password storage mechanism in Linux system In Linux system, the storage of user password is one of the very important security mechanisms. This article will analyze the storage mechanism of user passwords in Linux systems, including the encrypted storage of passwords, the password verification process, and how to securely manage user passwords. At the same time, specific code examples will be used to demonstrate the actual operation process of password storage. 1. Encrypted storage of passwords In Linux systems, user passwords are not stored in the system in plain text, but are encrypted and stored. L

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan
