Home Backend Development Python Tutorial Django project practical user avatar upload and access

Django project practical user avatar upload and access

Apr 21, 2018 pm 02:49 PM
django avatar user

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>
Copy after login

urls.py

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

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;)
Copy after login

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;)
Copy after login

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;)
Copy after login

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类似,指定用户可以通过这个路径找到文件
Copy after login

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}),
Copy after login

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>
Copy after login

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;)
Copy after login

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>
Copy after login

##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 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Xiaohongshu account to find users? Can I find my mobile phone number? How to use Xiaohongshu account to find users? Can I find my mobile phone number? Mar 22, 2024 am 08:40 AM

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 &quot;Discover&quot; button in the lower right corner, and then select the &quot;Notes&quot; 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 &quot;Follow&quot; 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 &quot;Personal Information&quot;

Log in to Ubuntu as superuser Log in to Ubuntu as superuser Mar 20, 2024 am 10:55 AM

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

What is sudo and why is it important? What is sudo and why is it important? Feb 21, 2024 pm 07:01 PM

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 vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

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 Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

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

How to change account name and avatar in Win10 - Detailed step-by-step guide How to change account name and avatar in Win10 - Detailed step-by-step guide Jan 14, 2024 pm 01:45 PM

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 Analysis of user password storage mechanism in Linux system Mar 20, 2024 pm 04:27 PM

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 How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

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

See all articles