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.db import models
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
class UserManager(models.Manager): class CustomUserManager(UserManager):
def all(self): def all(self):
return super().all().filter(is_active=True) return super().all().filter(is_active=True)
...@@ -16,7 +16,7 @@ class UserManager(models.Manager): ...@@ -16,7 +16,7 @@ class UserManager(models.Manager):
class User(AbstractUser): class User(AbstractUser):
objects = UserManager() objects = CustomUserManager()
class Profile(models.Model): class Profile(models.Model):
......
from rest_framework import serializers 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): class ArticleSerializer(serializers.ModelSerializer):
...@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer): ...@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
fields = ['id', 'title', 'text', 'author', 'status', 'created_at', 'updated_at'] fields = ['id', 'title', 'text', 'author', 'status', 'created_at', 'updated_at']
class ArticleSerializerOld(serializers.Serializer): class AuthorGetSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True) class Meta:
title = serializers.CharField(max_length=200, required=True) model = User
text = serializers.CharField(max_length=3000, required=True) fields = ['username', 'email']
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): class CommentGetSerializer(serializers.ModelSerializer):
return Article.objects.create(**validated_data) 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() class ArticleGetSerializer(serializers.ModelSerializer):
return instance 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 from api import views
router = routers.DefaultRouter()
router.register('article', views.ArticleViewSet)
urlpatterns = [ urlpatterns = [
path('echo', views.echo_view), path('', include(router.urls)),
path('articles', views.ArticlesView.as_view()), path('login', obtain_auth_token),
path('articles/<int:id_>', views.ArticleUpdateView.as_view())
] ]
import json from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
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 api import serializers
from web.models import Article from web.models import Article
@ensure_csrf_cookie class ArticleViewSet(ModelViewSet):
def echo_view(request, *args, **kwargs): queryset = Article.objects.all()
answer = { serializer_class = serializers.ArticleSerializer
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), lookup_url_kwarg = 'id'
'method': request.method, method_serializers = {
'get': serializers.ArticleGetSerializer,
'patch': serializers.ArticlePartialUpdateSerializer,
} }
permission_classes = (
print(request.body) permissions.AllowAny,
permissions.IsAdminUser,
if request.method == 'POST': permissions.IsAuthenticatedOrReadOnly,
if request.body: permissions.DjangoModelPermissions,
answer['content'] = json.loads(request.body) permissions.DjangoModelPermissionsOrAnonReadOnly,
)
return JsonResponse(answer)
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
class ArticlesView(APIView): return []
def get(self, request, *args, **kwargs): return super().get_permissions()
qs = Article.objects.all()
serializer = serializers.ArticleSerializer(qs, many=True) def get_serializer_class(self):
return JsonResponse(serializer.data, safe=False) method = self.request.method.lower()
if method in self.method_serializers:
def post(self, request, *args, **kwargs): return self.method_serializers.get(method)
data = json.loads(request.body)
serializer = serializers.ArticleSerializer(data=data) return self.serializer_class
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_)
$('#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 = [ ...@@ -42,6 +42,7 @@ INSTALLED_APPS = [
'django_extensions', 'django_extensions',
'rest_framework', 'rest_framework',
'rest_framework.authtoken',
'web', 'web',
'accounts', 'accounts',
'api', 'api',
...@@ -151,3 +152,15 @@ LOGIN_URL = 'login' ...@@ -151,3 +152,15 @@ LOGIN_URL = 'login'
# LOGOUT_REDIRECT_URL = 'main_page' # LOGOUT_REDIRECT_URL = 'main_page'
faker = Faker() faker = Faker()
# REST FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
...@@ -10,12 +10,14 @@ ...@@ -10,12 +10,14 @@
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous" referrerpolicy="no-referrer"/> crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="{% static 'css/styles.css' %}"> <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> <title>Title</title>
</head> </head>
<body> <body>
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container"> <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" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <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