Commit 7ef9d749 authored by Давид Ли's avatar Давид Ли

lesson 69

parent 666d57fd
from rest_framework import serializers
from web.models import StatusChoices, Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ['id', 'title', 'text', 'author', 'status', 'created_at', 'updated_at']
read_only_fields = ['author', 'id', 'created_at', 'updated_at']
class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=200, required=False)
text = serializers.CharField(max_length=3000, required=False)
class Meta:
model = Article
fields = ['id', 'title', 'text', 'author', 'status', 'created_at', 'updated_at']
class ArticleSerializerOld(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(max_length=200, required=True)
text = serializers.CharField(max_length=3000, required=True)
author = serializers.PrimaryKeyRelatedField(read_only=True)
status = serializers.ChoiceField(choices=StatusChoices.choices, required=False)
created_at = serializers.DateTimeField(read_only=True)
updated_at = serializers.DateTimeField(read_only=True)
def create(self, validated_data):
return Article.objects.create(**validated_data)
def update(self, instance, validated_data):
for k, v in validated_data.items():
setattr(instance, k, v)
instance.save()
return instance
......@@ -4,5 +4,6 @@ from api import views
urlpatterns = [
path('echo', views.echo_view),
path('articles', views.articles_view),
path('articles', views.ArticlesView.as_view()),
path('articles/<int:id_>', views.ArticleUpdateView.as_view())
]
import json
from django import http
from django.core.serializers import serialize, deserialize
from django.http import JsonResponse, HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from datetime import datetime
from django.views.decorators.csrf import ensure_csrf_cookie
from api import serializers
from web.models import Article
......@@ -26,20 +27,44 @@ def echo_view(request, *args, **kwargs):
return JsonResponse(answer)
def articles_view(request, *args, **kwargs):
if request.method == 'GET':
qs = Article.objects.values()
return JsonResponse(list(qs), safe=False)
class ArticlesView(APIView):
def get(self, request, *args, **kwargs):
qs = Article.objects.all()
serializer = serializers.ArticleSerializer(qs, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
serializer = serializers.ArticleSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, safe=False)
else:
return JsonResponse(status=400, data={'errors': serializer.error_messages})
if request.body:
try:
article = Article.objects.create(**json.loads(request.body))
except TypeError:
return http.HttpResponseBadRequest('invalid request body')
return JsonResponse({'id': article.id, 'title': article.title, 'text': article.text})
class ArticleUpdateView(APIView):
def update(self, request, id_, partial: bool = True):
serializer = serializers.ArticleSerializer
if partial:
serializer = serializers.ArticlePartialUpdateSerializer
instance = Article.objects.get(id=id_)
data = json.loads(request.body)
serializer = serializer(data=data, instance=instance)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, safe=True)
else:
return JsonResponse(status=400, data={'error': 'No data provided!'})
return JsonResponse(status=400, data={'errors': serializer.error_messages})
def put(self, request, id_: int, *args, **kwargs):
return self.update(request, id_, partial=False)
def patch(self, request, id_, *args, **kwargs):
return self.update(request, id_)
......@@ -40,7 +40,8 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'rest_framework',
'web',
'accounts',
'api',
......
......@@ -7,6 +7,7 @@ curtsies==0.4.1
cwcwidth==0.1.8
Django==3.2.19
django-extensions==3.2.3
djangorestframework==3.14.0
greenlet==2.0.2
idna==3.4
Pillow==10.0.0
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment