article

Wednesday, May 13, 2020

Django File Upload - How to upload file simple and Model Form


Django File Upload - How to upload file simple and Model Form

You will learn the conecepts django file upload

Need to set MEDIA_URL and MEDIA_ROOT in your project’s settings.py.

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


MEDIA_URL in template you must add django.template.context_processors.media to your context_processeors inside the TEMPLATES config.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')], 
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
            ],
        },
    },
]
#view.py
from django.shortcuts import render, redirect

from django.conf import settings
from django.core.files.storage import FileSystemStorage

from myapp.models import Document
from myapp.forms import DocumentForm

def home(request):
    documents = Document.objects.all()
    return render(request, 'home.html', { 'documents': documents })


def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'simple_upload.html')


def model_form_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = DocumentForm()
    return render(request, 'model_form_upload.html', {
        'form': form
    })
#models.py
from django.db import models
 
class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
 
    class Meta:  
        db_table = "myapp_document"
#forms.py
from django import forms
from myapp.models import Document
 
class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.home),
    path('simple_upload/',views.simple_upload),
    path('model_form_upload/',views.model_form_upload),
]
//templates/home.html
{% extends 'base.html' %}

{% block content %}
 <p><a href="/simple_upload" class="btn btn-primary">Simple Upload</a></p>
 <p><a href="/model_form_upload" class="btn btn-info">Model Form Upload</a></p>

 <p>Uploaded files:</p>
 <ul>
    {% for obj in documents %}
      <li>
        <a href="{{ obj.document.url }}">{{ obj.document.name }}</a>
        <small>(Uploaded at: {{ obj.uploaded_at }})</small>
      </li>
    {% endfor %}
 </ul>
{% endblock %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django File Upload{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
 <div class="container">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django File Upload - How to upload file simple and Model Form</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %}
 
        {% endblock %}
    </div>
    </div>
</body>
</html>
//templates/model_form_upload.html
{% extends 'base.html' %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Upload</button>
  </form>
<br/>
  <p><a href="/">Return to home</a></p>
{% endblock %}
//templates/simple_upload.html
{% extends 'base.html' %}

{% load static %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile" class="form-control">
    <button type="submit" class="btn btn-primary">Upload</button>
  </form>

  {% if uploaded_file_url %}
    <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
  {% endif %}
<br/>
  <p><a href="/">Return to home</a></p>
{% endblock %}

Related Post