13. Django Python – Upload Image

django python bahasa indonesia

Upload Image

  1. Pastikan config untuk media sudah ada di settings.py.
...
 MEDIA_URL = '/media/'
 MEDIA_FILES = os.path.join(BASE_DIR, 'media'),

2. Tambahkan config di settings.py.

TEMPLATES = [
...
    'Django.template.context_processors.media',
...
]

3. Install pillow.

$ pip install pillow

4. Buat folder foto di dalam folder media.
5. Tambahkan field untuk image pada models.py.

...
   foto = models.ImageField(upload_to='foto/', null=True)

6. Apply model ke database.

$ python3 manage.py makemigrations
$ python3 manage.py migrate

7. Edit views tambah_siswa & edit_siswa.

def tambah_siswa(request):
   if request.POST:
      form = FormSiswa(request.POST, request.FILES)
...
...

def edit_siswa(request, nomor_siswa):
   list_siswa = Siswa.objects.get(id=nomor_siswa)
   template = 'edit-siswa.html'
   if request.POST:
      form = FormSiswa(request.POST, request.FILES, instance=siswa)
...

8. Edit form pada html tambah-siswa.html & edit-siswa.html.

<form action="{% url 'tambah_siswa' %}" method="POST" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button class="btn btn-primary">Tambah</button>
      <a href="{% url 'siswa' %}" class="btn btn-light">Kembali</a>
</form>

Menampilkan Image

  1. Edit urls.py.
from django.conf.urls.static import static


urlpatterns = [
...
]

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

2. Tampilkan di file html.

{% if siswa.foto %}
   <img src="{{ siswa.foto.url }}" style="height: 200px; width: 150px;">
{% endif %}

Lanjutkan Membaca Materi Lengkap


Leave a Reply

Your email address will not be published. Required fields are marked *

seventeen + seven =

This site uses Akismet to reduce spam. Learn how your comment data is processed.