Using Image in the Post with Django

We came how to use image in Django. We made a comment section for our blog, and we could add comment to the posts as well. An image file is actually static files. But, I'm not store them into the static folder, I will stored these files in folder called media. Why? Because the files will be uploaded from user. We don't use it for template design. If we use image for web design, then we should put on it in static folder. Firstly, I created A media folder in project base dir. After creating file, open the settings.py file from project folder:

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

MEDIA_URL = '/media/'
We need to add this media folder url to the main urls.py file:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myblog.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, let's edit our post model in the models.py:
class Post(models.Model):
    title = models.CharField(max_length=400)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    categories = models.ManyToManyField(Category)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='images/', null=True)
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ['-pub_date',]
We have already defined media folder and upload_to makes the images will be uploaded to media/images/ automatically. Let's save this model in the database because we changed it:

 
upload image in Django

I uploaded an example image from the admin panel. You can see this image  is uploaded in the images folder in the media folder.

Let's show this image in the detail page of each post, if it exist. I will open the detail.html file and I will edit like that:
{% extends '_base_layout.html' %}

{% block content %}
<div class="row">
    <div class="col-sm-9">
        <div class="page">
            <h5 class="post-title">{{ post.title }}</h5>
            {% if post.image  %}
            <div class="post-image">
                <img src="{{ post.image.url }}">
            </div>
        {% endif %}
            <p>{{ post.content }}</p>
        </div>
        {% include 'comment.html' %}
    </div>
    <div class="col-sm-3">
        sidebar
    </div>
</div> 
{% endblock %}
The result is like that:
Uploaded Image in Django
That's nice. If you get the error about pillow, you have to install pillow module as a solution.

But this is not for production Django project. This post is just for development stage of Django.

No comments:

Post a Comment