A website without images would probably be the worst thing on the Internet today.
And even with that fact, some developers do not know how to add images to a website.
Here is how to do that using the django admin panel.
Let's use a model class name profile.
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
First thing we have to do is to add image field to the class
image = models.ImageField(null=True, blank=True)
We have to add the pillow package, the python Imaging Library is a free and open-source extension library for Python that adds support for accessing, processing, and saving a wide range of image file types.
We can the install the pillow package by running this command
pip install pillow
We can proceed by adding the data to the database by running the migrations
python manage.py makemigrations
python manage.py migrate
The next step is to update the media url and root. By doing this, we are telling django where to store the images. You should add this to the settings.py file
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
We should head to the site's urls.py file and import some packages
from django.conf.urls.static import static
from django.conf import settings
This is how it should look like.
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path(' ', include('store.urls')),
]
Then we add this to the urls.py file. This is to add a route for the images
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After this,we can upload the image using the django admin panel.
Finally, we can render the image on the html file.
<img class="thumbnail" src="{{profile.image.url}}">
Bonus Tip
What if the image was deleted or missing. We would not want the entire website to suddenly stop working.
There are two ways of going around this error
1. Add a property decorator to the model class
@property
def imageURL(self):
try:
url = self.image.url
execpt:
url = ""
return url
2. Use an IF statement
{% if product.image %}
<img class="thumbnail" src="{{profile.image.url}}">
{% else %}
<img class="thumbnail" src="{% static 'images/placeholder. png %}">
{% endif %}
Top comments (0)