Django | Media 업로드

13648 단어 djangopythondjango

목표: 사진 성공적으로 업로드하기

  • config/utils.py
import os
from uuid import uuid4


def uuid_upload_to(instance, filename):
    uuid_name = uuid4().hex
    ext = os.path.splitext(filename)[-1].lower()
    return '/'.join([
        uuid_name[:2],  # 256가지 조합
        uuid_name[2:4],
        uuid_name[4:] + ext
    ])



  • shop/models.py
from django.db import models
from askcompany.utils import uuid_upload_to

class Item(models.Model):
    name = models.CharField(max_length=100)
    desc = models.TextField(blank=True)
    price = models.PositiveIntegerField()
    photo = models.ImageField(blank=True, upload_to=uuid_upload_to)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_publish = models.BooleanField(default=False)

    def __str__(self):
        return f'<{self.pk}> {self.name}'
        # return '<{}> {}'.format(self.pk, sel.name)

    def get_absolute_url(self):
        # return reverse('shop:item_detail', args=[self.pk])
        return reverse('shop:item_detail', kwargs={'pk': self.pk})
        
        
        
  • config/urls.py
from django.conf import settings
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
from django.conf.urls.static import static
from django.shortcuts import redirect

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', lambda req: redirect('blog:post_list'), name='root'),
    path('shop/', include('shop.urls')),
    path('blog/', include('blog.urls')),
    path('accounts/', include('accounts.urls')),
]

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

        
        
        
  • shop/templates/shop/item_detail.html
{% extends 'shop/layout.html' %}
{% load humanize %}

{% block content %}
  <h2>{{ item.name }}</h2>

  # 미디어를 추가한 부분
  {% if item.photo %}
      <img src="{{ item.photo.url }}" style="max-width: 100%"><br>
  {% endif %}

  가격: {{item.price| intcomma }}{% if item.desc %}
      <p>{{ item.desc }}</p>
  {% endif %}

  <hr>
  <a href="/shop/">목록</a>

{% endblock %}

좋은 웹페이지 즐겨찾기