In this tutorial, we will learn how to upload media files such as images, files, etc.
It is generally the most common requirement in any modern web application is the ability to take files like profile pictures, pdf, word docs, and images from the user and save the theme on the server.
Django has two model fields such as FileField and ImageField.
The uploaded files are stored in the file system, not in the database. Now we can create a string field to reference to the file or image.
HTML
It is mandatory for the html form to have the attribute enctype=”mulipart/form-data”.
The form must be POST method to submit the form.
Django File Upload
fileupload.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} {% block content %} <div class="row"> <div class="col-md-6 col-xs-12"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="fileupload" class="form-control"> <button type="submit" class="btn btn-success">submit</button> </form> {% if uploaded_url %} <p>File Uploaded at :<a href ="{{uploaded_url}}">{{ uploaded_url }}</a></p> {% endif %} </div> </div> {% endblock %}
Django
You will need to set MEDIA_URL and MEDIA_ROOT in your projects.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
And now add the following configuration in the projects urls.py files
urls.py
from django.conf import settings from django.conf.urls.static import static urlpatterns = [] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
File Upload using File System Storage
views.py
from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage def File_Upload(request): try: if request.method == 'POST' and request.FILES['fileupload']: pfile = request.FILES['fileupload'] filesys =FileSystemStorage() uploadfilename = filesys.save(pfile.name,pfile) uploaded_url = filesys.url(uploadfilename) return render(request, 'fileupload.html' ,{'uploaded_url':uploaded_url}) except Exception as identifier: print(identifier) return render(request,'fileupload.html',{})
Uploading Files with Model Form
Let’s start by creating models.
models.py
class Files(models.Model): filename = models.CharField(max_length=150) uploadimage = models.ImageField(upload_to='profile_pic') def __str__(self): return self.filename
forms.py
from .models import Files class employeeprofile(forms.ModelForm): class Meta: model = Files fields = ('filename','uploadimage')
views.py
from .forms import employeeprofile def File_upload_model(request): form = employeeprofile() try: if request.method == 'POST': form = employeeprofile(request.POST, request.FILES) if form.is_valid(): form.save() profile_pic = form.instance return render(request, 'empprofile.html',{'form':form,'profile_pic':profile_pic}) else: form = employeeprofile() return render(request , 'empprofile.html',{'form':form}) except Exception as identifier: print(identifier) return render(request,'empprofile.html',{'form':form})
urls.py
from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('File_Upload/', views.File_Upload,name="File_Upload"), path('File_upload_model/', views.File_upload_model,name="File_upload_model"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
HTML – empprofile.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} {% block content %} <div class="row"> <div class="col-md-6 col-xs-12"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <button type="submit" class="btn btn-success">submit</button> </form> {% if profile_pic %} <p>File Uploaded at :<a href ="{{profile_pic.filename}}">{{ profile_pic.filename }}</a></p> <img src="{{profile_pic.upload_image.url}}" alt ="connect" style="max-height:300px"> {% endif %} </div> </div> {% endblock %}