Commit 18c1d616 authored by Давид Ли's avatar Давид Ли

lesson 71

parent 8efb80b4
from django.contrib.auth import get_user_model
from rest_framework import serializers
from webapp import models
from accounts import models as accounts_models
class _ArticleSerializer(serializers.Serializer):
......@@ -21,9 +23,35 @@ class _ArticleSerializer(serializers.Serializer):
instance.save()
return instance
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = accounts_models.Profile
fields = ['birth_date', 'avatar']
class _UserSerializer(serializers.ModelSerializer):
fullname = serializers.SerializerMethodField()
class Meta:
model = get_user_model()
fields = ['id', 'fullname', 'first_name', 'last_name', 'email', 'username']
def get_fullname(self, obj):
return f'{obj.first_name} {obj.last_name}'
class ArticleSerializer(serializers.ModelSerializer):
author = _UserSerializer(read_only=True)
class Meta:
model = models.Article
fields = ['id', 'title', 'text', 'author', 'created_at', 'updated_at']
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
articles = ArticleSerializer(many=True)
class Meta:
model = get_user_model()
fields = ['id', 'first_name', 'last_name', 'email', 'username', 'profile', 'articles']
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register('articles', views.ArticleViewset)
router.register('users', views.UserViewset)
import json
from django.views.generic import View
from rest_framework.views import APIView
from django.contrib.auth import get_user_model
from rest_framework import views, viewsets, permissions
from rest_framework.response import Response
from api import serializers
from webapp import models
class ArticleListView(APIView):
def get(self, request, *args, **kwargs):
articles = models.Article.objects.all()
serializer = serializers.ArticleSerializer(articles, many=True)
return Response(serializer.data, safe=False)
class ArticleViewset(viewsets.ModelViewSet):
queryset = models.Article.objects.all()
serializer_class = serializers.ArticleSerializer
permission_classes = [permissions.IsAuthenticated]
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return []
return super().get_permissions()
class UserViewset(viewsets.ModelViewSet):
queryset = get_user_model().objects.all()
serializer_class = serializers.UserSerializer
class LogoutAPIView(views.APIView):
permission_classes = []
class ArticleCreateView(APIView):
def post(self, request, *args, **kwargs):
serializer = serializers.ArticleSerializer(data=json.loads(request.body))
user = request.user
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
if user.is_authenticated:
user.auth_token.delete()
return Response(serializer.errors, status=400)
return Response({'status': 'ok'})
......@@ -25,7 +25,10 @@ SECRET_KEY = 'django-insecure-ao+ma%k=n3c2^tsc4wicjqho8_60d2ja1m9ne+m6k&p8%y=^yo
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['*']
CORS_ALLOWED_ORIGINS = [
'http://localhost:52330',
]
# Application definition
......@@ -39,6 +42,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'api',
'webapp',
......@@ -48,6 +53,7 @@ INSTALLED_APPS = [
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
......@@ -149,3 +155,14 @@ MEDIA_URL = '/images/'
SESSION_COOKIE_AGE = 5 * 60
# DATE_INPUT_FORMATS = ('%d.%m.%Y',)
# REST FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
......@@ -2,7 +2,9 @@ from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework.authtoken.views import obtain_auth_token
from api.urls import router
from api import views as api_views
from webapp import views
......@@ -11,6 +13,7 @@ urlpatterns = [
path('', views.IndexRedirectView.as_view(), name='redirect_to_index'),
path('articles/', include('webapp.urls')),
path('accounts/', include('accounts.urls')),
path('api/articles/', api_views.ArticleListView.as_view()),
path('api/articles/create', api_views.ArticleCreateView.as_view()),
path('api/', include(router.urls)),
path('api/login/', obtain_auth_token, name='api_token_auth'),
path('api/logout/', api_views.LogoutAPIView.as_view(), name='api_logout'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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