티스토리 뷰

파이썬/장고

DRF IMAGE 복수 처리

글을 쓰는 개발자 2021. 6. 22. 20:46
반응형

1단계(설치)

pip instll Pillow django djangorestframework

2단계(설치)

django-admin startproject backend .
django-admin startapp blog

3단계(settings.py)

INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'blog.apps.BlogConfig'
]

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

4단계(backend.urls.py)

from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include('blog.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

5단계

Models

from django.db import models

class Blog(models.Model):
    title=models.CharField(max_length=25)

    def __str__(self) -> str:
        return self.title

class Image(models.Model):
    blogId=models.ForeignKey(Blog,on_delete=models.CASCADE)
    image=models.ImageField(default='media/제목없음.jpeg',upload_to="")

Serializers

from django.db import models
from django.db.models import fields
from rest_framework import serializers
from .models import Image,Blog

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ['image']
    
class BlogSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True,read_only=True)
    class Meta:
        model = Blog
        fields= ('id','title','images')
    
    def create(self,validated_data):
        images_data = self.context['request'].FILES
        blog = Blog.objects.create(**validated_data)
        for image_data in images_data.getlist('images'):
            Image.objects.create(blogId=blog,image=image_data)
        return blog

Views

from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from .models import Blog
from .serializers import BlogSerializer
from rest_framework.response import Response
class BlogViewSet(ModelViewSet):
    permission_classes = (permissions.AllowAny,)
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    def create(self,request,*args,**kwargs):
        response=super().create(request,*args,**kwargs)
        return Response({'success':True})

Urls

from django.db import router
from django.urls import path
from django.urls.conf import include
from rest_framework.routers import DefaultRouter
from .views import BlogViewSet
router = DefaultRouter()
blog_list = BlogViewSet.as_view({"get": "list", "post": "create"})
blog_detail = BlogViewSet.as_view(
    {"get": "retrieve", "patch": "partial_update", "delete": "destroy"})
urlpatterns = [
    path('upload', blog_list, name="blog_list"),
    path('blog/<int:pk>', blog_detail)
]

Github 주소: https://github.com/VIXXPARK/django-remind/tree/main/django-image-post

 

VIXXPARK/django-remind

Contribute to VIXXPARK/django-remind development by creating an account on GitHub.

github.com

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함