Commit 89cd7948 authored by Давид Ли's avatar Давид Ли

lesson 70

parent 7ef9d749
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.contrib.auth import get_user_model
class UserManager(models.Manager):
class CustomUserManager(UserManager):
def all(self):
return super().all().filter(is_active=True)
......@@ -16,7 +16,7 @@ class UserManager(models.Manager):
class User(AbstractUser):
objects = UserManager()
objects = CustomUserManager()
class Profile(models.Model):
......
from rest_framework import serializers
from web.models import StatusChoices, Article
from accounts.models import User
from web.models import StatusChoices, Article, Comment
class ArticleSerializer(serializers.ModelSerializer):
......@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
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)
class AuthorGetSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'email']
def create(self, validated_data):
return Article.objects.create(**validated_data)
class CommentGetSerializer(serializers.ModelSerializer):
author = AuthorGetSerializer()
class Meta:
model = Comment
fields = ['text', 'author', 'created_at', 'updated_at']
def update(self, instance, validated_data):
for k, v in validated_data.items():
setattr(instance, k, v)
instance.save()
return instance
class ArticleGetSerializer(serializers.ModelSerializer):
author = AuthorGetSerializer()
comments = CommentGetSerializer(many=True)
class Meta:
model = Article
fields = [
'id', 'title',
'text', 'author',
'status', 'comments',
'created_at', 'updated_at',
]
#
# class CommentsCreateSerializer(serializers.ModelSerializer):
# class Meta:
# model = Comment
# fields = ['text', 'author']
# class ArticleCreateSerializer(serializers.ModelSerializer):
# comments = CommentsCreateSerializer(many=True)
#
# class Meta:
# model = Article
# fields = ['title', 'text', 'author', 'status', 'comments']
from django.urls import path
from django.urls import path, include
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from api import views
router = routers.DefaultRouter()
router.register('article', views.ArticleViewSet)
urlpatterns = [
path('echo', views.echo_view),
path('articles', views.ArticlesView.as_view()),
path('articles/<int:id_>', views.ArticleUpdateView.as_view())
path('', include(router.urls)),
path('login', obtain_auth_token),
]
import json
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 rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from api import serializers
from web.models import Article
@ensure_csrf_cookie
def echo_view(request, *args, **kwargs):
answer = {
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'method': request.method,
class ArticleViewSet(ModelViewSet):
queryset = Article.objects.all()
serializer_class = serializers.ArticleSerializer
lookup_url_kwarg = 'id'
method_serializers = {
'get': serializers.ArticleGetSerializer,
'patch': serializers.ArticlePartialUpdateSerializer,
}
print(request.body)
if request.method == 'POST':
if request.body:
answer['content'] = json.loads(request.body)
return JsonResponse(answer)
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)
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})
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={'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_)
permission_classes = (
permissions.AllowAny,
permissions.IsAdminUser,
permissions.IsAuthenticatedOrReadOnly,
permissions.DjangoModelPermissions,
permissions.DjangoModelPermissionsOrAnonReadOnly,
)
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return []
return super().get_permissions()
def get_serializer_class(self):
method = self.request.method.lower()
if method in self.method_serializers:
return self.method_serializers.get(method)
return self.serializer_class
$('#articlesMain').on('click', async function (event) {
event.preventDefault()
let token
await $.ajax({
url: '/api/login',
method: 'post',
data: JSON.stringify({username: 'admin', password: 'root'}),
contentType: 'application/json'
})
.then(function (resp) {token = resp.token})
await $.ajax({
url: '/api/article',
method: 'get',
headers: {Authorization: 'Token ' + token}
}).then(resp => console.log(resp))
})
......@@ -42,6 +42,7 @@ INSTALLED_APPS = [
'django_extensions',
'rest_framework',
'rest_framework.authtoken',
'web',
'accounts',
'api',
......@@ -151,3 +152,15 @@ LOGIN_URL = 'login'
# LOGOUT_REDIRECT_URL = 'main_page'
faker = Faker()
# REST FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
......@@ -10,12 +10,14 @@
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{% static 'js/main.js' %}" defer></script>
<title>Title</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="{% url 'main_page' %}">Articles</a>
<a class="navbar-brand" href="{% url 'main_page' %}" id="articlesMain">Articles</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
......
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