Django File Uploading - How to Upload File without Form | W3schools

This feature of a web application enables it to upload a file (such as an image, document, video, etc.). In this chapter, we will help you understand how to upload files within an application.

Also Read: Django Generic Views

How To Upload An Image?

For this feature to work, you are required to have a pre-installed Python Image Library (PIL). With the help of the following coding section, you will be able to create a profile form within the already created myapp/forms.py file. This section of code will help you upload an image in the application.

#-*- coding: utf-8 -*-
from django import forms 
class ProfileForm(forms.Form):
   name = forms.CharField(max_length = 100)
   picture = forms.ImageFields() 

Here, you can see an additional function which is forms.ImageFields(). This function ensures that the uploaded file satisfies the condition of being an image. If the user tries to upload a file which is not supported by the function then the whole process of validation fails.

The other section of code will help you to save the uploaded file. For this purpose, you are required to make use of myapp/models.py file.

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” 

The above code clearly clarifies that in the myapp/models.py file, the ImageField compulsorily accepts an argument, which is upload_to. This variable is a representation of the path where a user’s uploaded image is stored.

Note: This parameter will later be added to the MEDIA_ROOT option. You can easily locate this option under the myapp/settings.py file.

After the creation of the Model and the required Form, it’s time to alter the coding under the myapp/views.py file.

#-*- 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())

You should take a note of request.FILES parameter. This is an additional parameter which is required when you are creating a profile form. If the user doesn’t pass a parameter to it then the process of validation will eventually fail. It will also display a message indicating the picture is empty.

Once you are done with all of the above changes, start by creating the saved.html and profile.html templates. The saved.html template will support the form while profile.html template will act as the redirection page. You can locate both of these files under myapp/templates/ path. 

myapp/templates/saved.html
<html>
   <body>   
      {% if saved %}
         <strong>Your profile was saved.</strong>
      {% endif %}      
      {% if not saved %}
         <strong>Your profile was not saved.</strong>
      {% endif %}      
   </body>
</html>
myapp/templates/profile.html
<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>

 

At the final step, we need to update the myapp/urls.py file. For that, you need to make following changes in your urls.py file.

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.html’)), url(r’^saved/’, ‘SaveProfile’, name = ‘saved’)
)

Now, enter the given URL: http://127.0.0.1:8000/myapp/profile in your web browser. The screen will display the following profile.html template.

And while accessing the form post, you will get the following screen which is the result of the saved.html template.

This above coding will help you to upload an image. But, in case, if you want to upload another type of file then you just need to replace ImageField with the FileField parameter. And make sure that the all the required changes take place on both the Model and the Form files.