# myapp/models.py
from django.db import models
class Post(models.Model):
message = models.TextField()
# myapp/forms.py
from django import forms
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
# myapp/views.py
def post_list(request):
if request.method == 'POST’:
# 새 글 저장을 구현
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save()
return JsonResponse(post)
return JsonResponse(form.errors)
else:
# 목록 응답을 구현
return JsonResponse(Post.objects.all())
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'PUT’:
# 특정 글 갱신을 구현
put_data = QueryDict(request.body)
form = PostForm(put_data, instance=post)
if form.is_valid():
post = form.save()
return JsonResponse(post)
return JsonResponse(form.errors)
elif request.method == 'DELETE’:
# 특정 글 삭제를 구현
post.delete()
return HttpResponse()
else:
# 특정 글 내용 응답을 구현
return JsonResponse(post)
urlpatterns = [
...
path('api-auth/', include('rest_framework.urls'))
]
from django.conf.urls import url
from django.contrib.auth import views
app_name = 'rest_framework'
urlpatterns = [
url(r'^login/$', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'),
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
]
https://www.django-rest-framework.org/#installation
# myapp/models.py
from django.db import models
class Post(models.Model):
message = models.TextField()
# myapp/serializers.py
from rest_framework import serializers
from .forms import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
# myapp/views.py
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
# myapp/urls.py
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('posts', views.PostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
쉘> http GET 요청할주소 GET인자명==값 GET인자명==값
쉘> http --json POST 요청할주소 GET인자명==값 GET인자명==값 POST인자명=값 POST인자명=값
쉘> http --form POST 요청할주소 GET인자명==값 GET인자명==값 POST인자명=값 POST인자명=값
쉘> http PUT 요청할주소 GET인자명==값 GET인자명==값 PUT인자명=값 PUT인자명=값
쉘> http DELETE 요청할주소 GET인자명==값 GET인자명==값
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def dispatch(self, request, *args, **kwargs):
print("request.body:", request.body)
print("request.POST:", request.POST)
return super().dispatch(request, *args, **kwargs)