티스토리 뷰
반응형
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
반응형
'파이썬 > 장고' 카테고리의 다른 글
django test response body 가져오기 (0) | 2021.07.09 |
---|---|
Django user 비밀번호 암호화 (0) | 2021.07.06 |
Django kakao OAuth login 구현 (0) | 2021.06.29 |
django nested/foreign key 관계 모델까지 가져오기 (0) | 2021.06.23 |
django simple-jwt payload 확장하기 (0) | 2021.06.22 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- dockerignore
- Collections
- DRF
- 알고리즘
- thread
- env
- PostgreSQL
- 프로그래머스
- postgres
- docker-compose
- ubuntu
- headers
- Python
- Celery
- 카카오
- BFS
- docker
- django
- 백준
- Linux
- Spring
- 자바
- Java
- 그래프
- Command Line
- Pattern
- 면접
- setattr
- 파이썬
- 2021 KAKAO BLIND RECRUITMENT
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함