Django

File Uploading in Django

File Uploading in Django

This functionality is used to upload files such as profile pictures, images or videos that we post on social media apps, songs, ppts, pdfs, etc. In this section, we are going to learn how we can create a Django app for uploading a picture. There’s a prerequisite needed to start working with File uploading in Django and that is PIL (Python Image Library). You need to install this library first and can follow it further. 

Let’s create a form for the image and profile name under firstapp/forms.py:

from django import forms
class ImageForm (forms.Form)
u_name = forms.CharField(max_length = 40)
pic = forms.ImageField()

The only difference that can be noticed here is the forms.ImageField. It will validate if the image is uploaded or not and when the image is not uploaded, it fails validation. 

Now, we are going to create a ‘Profile’ model that will save the image and profile name. To do that, we are going to create a model in the firstapp/models.py file:

from django.db import models
class MyProfile (models.Model):
u_name = models.CharField(max_length = 40)
pic = models.ImageField(upload_to = ‘profile_pic’)
class meta:
database_table = “profile”

Here, the ‘upload_to’ argument will upload the image to provided place on the hard drive. Now, we have the form and the Model, we are going to create the view in firstapp/views.py:

from firstapp.forms import ImageForm
from firstapp.models import MyProfile
def SaveMyProfile (request):
saved = False
if request.method == “POST”:
MyImageProfile = ImageForm (request.POST, request.FILES)
if MyImageProfile.is_valid():
my_profile = MyProfile()
my_profile.name = MyImageProfile.cleaned_data[“u_name”]
my_profile.picture = MyImageProfile.cleaned_data[“pic”]
my_profile.save()
saved = True
else:
MyImageProfile = ImageForm()
return render (request, ‘saveimage.html’, locals())

In the view created above, a second parameter is created, i.e. request.FILES. If the second parameter is not passed, then the form validation will fail for not providing the image. 

Now, we need two templates,  ‘saveimage.html’ and ‘imgprofile.html’ for the form and redirection of the page. 

firstapp/templates/saveimage.html
<html>
<body>
{% if saved %}
<strong>Profile is saved.</strong>
{% endif %}
{% if not saved %}
<strong>Profile not saved.</strong>
{% endif %}
</body>
</html>
firstapp/templates/imageprofile.html
<html>
<body>
<form name = “form” enctype = “multipart/form-data” action = “{% url “firstapp.views.SaveProfile” %} method = “POST” > {% csrf_token %}
<div style = "max-width:350px;">
            <center>  
               <input type = "text" style = "margin-left:18%;" 
               placeholder = "Name" name = "name" />
            </center>
         </div>
         <br>         
         <div style = "max-width:350px;">
            <center> 
               <input type = "file" style = "margin-left:18%;" 
                  placeholder = "Picture" name = "picture" />
            </center>
         </div>
         <br>         
         <div style = "max-width:350px;">
            <center>             
               <button style = "border:0px;margin-top:8%; 
                  height:30px; width:75%; margin-left:18%;" type = "submit" value = "Login" >
                  <strong>Login</strong>
               </button>
           </center>
         </div>         
      </form>     
   </body>
</html>

Now we are going to create a pair of URLs:

firstapp/urls.py
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
url_patterns = patterns(
‘firstapp.views’, url(r’^profile/’, TemplateView.as_view(
name_of_template = ‘imageprofile.html’)), url(r’^saved/’, ‘SaveProfile’, name = ‘saved’) 

To access the profile page, follow the URL below:

http://127.0.0.1:8000/firstapp/profile/

After saving the details, when you click on submit, the template saveimage.html will be triggered.

Top course recommendations for you

    Circular Queue
    1 hrs
    Beginner
    3K+ Learners
    4.52  (195)
    Python Stack
    2 hrs
    Beginner
    3.8K+ Learners
    4.52  (94)
    AI and Big Data in IOT
    1 hrs
    Intermediate
    7.8K+ Learners
    4.5  (495)
    Selenium Basics
    1 hrs
    Beginner
    20.9K+ Learners
    4.41  (1193)
    Selenium with Python
    1 hrs
    Beginner
    11K+ Learners
    4.39  (532)
    Selenium Projects with Python
    2 hrs
    Intermediate
    7.6K+ Learners
    4.54  (173)
    Java Projects
    1 hrs
    Beginner
    19.7K+ Learners
    4.17  (192)
    JDBC in Java
    1 hrs
    Beginner
    7.5K+ Learners
    4.45  (415)
    Flask Python
    1 hrs
    Beginner
    6.3K+ Learners
    4.3  (261)
    Linked List in Python
    3 hrs
    Beginner
    2.5K+ Learners
    4.61  (41)