Here is how I have things:
ImageField model (in models.py):
image_upload = models.ImageField(upload_to="images/", null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg'])])
Settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # the path becomes [project dir]\media\
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = "/static/"
VALID_IMAGE_EXTENSIONS = [
".jpg",
".jpeg",
".png",
".gif",
]
def valid_url_extension(url, extension_list=VALID_IMAGE_EXTENSIONS):
return any([url.endswith(e) for e in extension_list])
html markup with the image upload (using django ModelForm)
the form html options:
<form action="" method="post" class="row g-3 pb-4" enctype="multipart/form-data">
getting the data with the form:
<div class="card">
<div class="card-header">
{{ form.image_upload.label }} :
</div>
<div class="card-body">
{{form.image_upload}}
</div>
</div>
Form class (showing relevant code, bootstrap class in widget):
class RecordForm(ModelForm):
class Meta:
model = DashboardModel
fields = (
"image_upload",
)
labels = {
"image_upload" : "Images",
}
widgets = {
"image_upload" : forms.ClearableFileInput(attrs={'class':'form-control form-control-lg', 'placeholder':'images' }),
}
html markup for the image display (using bootstrap classes):
<div class="row">
<div class="col-sm-3">
<p class="mb-0">images</p>
</div>
<div class="col-sm-9">
<p class="text-muted mb-0">
{%if record.image_upload %}
<img src="{{ record.image_upload.url }}" height='430'>
{% endif %}
</p>
</div>
</div>
urls.py within my app called “dashboard” (showing relevant paths):
urlpatterns = [
path('dashboard/record_create/', RecordCreatePage.as_view(), name= 'record_create'),
path('dashboard/record_details/<str:pk>/', RecordDetailPage.as_view(), name="record_detail"),
path('dashboard/record_update/<str:pk>/', RecordUpdatePage.as_view(), name= 'record_update'),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urls.py outside of app (in project name folder):
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('dashboard.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am using:
Windows 10
Python 3.7.0
Pillow 8.2.0