Skip to content

Latest commit

 

History

History
84 lines (62 loc) · 1.87 KB

README.md

File metadata and controls

84 lines (62 loc) · 1.87 KB

How To Upload An Image to DRF Using Fetch API

Minimal Requirements

Packages

  • django
  • djangorestframework
  • django-cors-headers
  • Pillow

Convenience command

pip install django djangorestframework django-cors-headers Pillow

Settings

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'corsheaders'    
    # ...
]

MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #...
]



# Media settings (determines where images will be uploaded)

MEDIA_URL = 'media/'

MEDIA_ROOT = BASE_DIR / 'media'

# Cors (determines which urls can access your data. Only required for browser access)

CORS_ALLOW_ALL_ORIGINS = True  # Not required, but convenient for testing

config/urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ...
]

if settings.DEBUG:
    static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

const imageInput = document.querySelector('input') const imageList = document.querySelector('#imageList')

const imageFieldName = 'file' // Determined in by your Model with an ImageField or FileField (e.g., BlogPost.image <- Would be 'image')