Step 1:
$ pip install pillow
Step 2:
Add the model for the image in your apps models.py
class Imagemodel(models.Model):
# .....
pic = models.ImageField(upload_to='images/', null=True) # U can change to `FileField` for files
Step 3:
Make migrations and migrate:
$ py manage.py makemigrations && migrate
Step 4:
open settings.py and add the following code. This code tells Django where to store the images.
import os # at the top
# Other settings ..
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR , 'media')
Step 5:
In your project directory level, create the media folder:
$ mkdir media
Step 6:
Open the project level urls.py and add the code below to add our media folder to the static files.
# other imports
from . import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# URL patterns
urlpatterns +=staticfiles_urlpatterns()
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 7:
In your app directory level (newendpoint), add a forms.py file and add the code below:
from django import forms
from .models import *
class PicForm(forms.ModelForm):
class Meta:
model = Imagemodel
fields = ['pic']
Step 8:
In your app (newendpoint), create a folder called templates and add a file called pic.html inside. In pic.html, add the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
Step 9:
In your app's views.py add the code below:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
# Create your views here.
def pic_view(request):
if request.method == 'POST':
form = PicForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = PicForm()
return render(request, 'pic.html', {'form': form})
def success(request):
return HttpResponse('successfully uploaded')
Step 10:
In your app's urls.py add the code below:
# .. other imports
from django.urls import path
from .views import *
urlpatterns = [
path('image_upload', pic_view, name='image_upload'),
path('success', success, name='success'),
]
Step 11:
Run the server:
$ python3 manage.py runserver
Upload the image through:
http://127.0.0.1:8000/image_upload
STATIC...variables in your settings.py? Which ones? What are they set to?