English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
For web applications, it is usually very useful to be able to upload files (images, songs, PDF format, text......). Let's discuss in this section how to use Django to upload files.
Before starting the development of image upload, make sure that the Python image library (PIL) is already installed. Now let's explain how to upload images, let's create a configuration file format, in myapp/forms.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 #-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length= 100) picture = forms.ImageFields()
As you can see, the main difference here is just forms.ImageField. The ImageField field ensures that the uploaded file is an image. If not, the format validation will fail.
Now, let's create a "Profile" model to save the uploaded information in myapp/models.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from django.db import models class Profile(models.Model): name = models.CharField(max_length= 50) picture = models.ImageField(upload_to='pictures') class Meta: db_table = "profile"
As seen in the model, the ImageField uses the mandatory parameter: upload_to. This indicates the location on the hard drive where the image is saved. Note that this parameter will be added to the MEDIA_ROOT option defined in the settings.py file.
Now we have the form and the model, let's create the view in myapp/ views.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 #-*- coding: utf-8 -*- from myapp.forms import ProfileForm from myapp.models import Profile def SaveProfile(request): saved = False if request.method == "POST": # Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileform() return render(request, 'saved.html', locals())
Don't miss this part, create a ProfileForm and make some modifications, add a second parameter: request.FILES. If the form validation fails, give a message saying the image is empty.
Now, we only need saved.html template and profile.html template, form and redirect page -
myapp/templates/saved.html -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <html> <body> {% if saved %} <strong>Your profile was saved.</strong>/strong> {% endif %} {% if not saved %} <strong>Your profile was not saved.</strong>/strong> {% endif %} </body> </html>
myapp/templates/profile.html -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <html> <body> <form name = "form" enctype = "multipart/form-data" action = "{% url "myapp.views.SaveProfile" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left:20%;" placeholder = "Picture" name = "picture" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19"type = "submit" value = "Login"> <strong>Login</strong> </button> </center> </div> </form> </body> </html>
Next, we need to match the URLs to start: myapp/urls.py
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( 'myapp.views', url(r'^profile/', TemplateView.as_view( template_name = 'profile.htmll'/', 'SaveProfile', name = 'saved') )
When accessing"/myapp/profile", we will get the following profile.htmll template displayed −
After the format is submitted, the saved template will be displayed as follows −
Here we only explain the image upload example, but if you want to upload other types of files, just replace the ImageField in these two models and the FileField form.