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

lesson 71

parent 8efb80b4
from django.contrib.auth import get_user_model
from rest_framework import serializers from rest_framework import serializers
from webapp import models from webapp import models
from accounts import models as accounts_models
class _ArticleSerializer(serializers.Serializer): class _ArticleSerializer(serializers.Serializer):
...@@ -23,7 +25,33 @@ class _ArticleSerializer(serializers.Serializer): ...@@ -23,7 +25,33 @@ class _ArticleSerializer(serializers.Serializer):
return instance 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): class ArticleSerializer(serializers.ModelSerializer):
author = _UserSerializer(read_only=True)
class Meta: class Meta:
model = models.Article model = models.Article
fields = ['id', 'title', 'text', 'author', 'created_at', 'updated_at'] 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.contrib.auth import get_user_model
from django.views.generic import View from rest_framework import views, viewsets, permissions
from rest_framework.views import APIView
from rest_framework.response import Response from rest_framework.response import Response
from api import serializers from api import serializers
from webapp import models from webapp import models
class ArticleListView(APIView): class ArticleViewset(viewsets.ModelViewSet):
def get(self, request, *args, **kwargs): queryset = models.Article.objects.all()
articles = models.Article.objects.all() serializer_class = serializers.ArticleSerializer
serializer = serializers.ArticleSerializer(articles, many=True) permission_classes = [permissions.IsAuthenticated]
return Response(serializer.data, safe=False)
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): def post(self, request, *args, **kwargs):
serializer = serializers.ArticleSerializer(data=json.loads(request.body)) user = request.user
if serializer.is_valid(): if user.is_authenticated:
serializer.save() user.auth_token.delete()
return Response(serializer.data)
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 ...@@ -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! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = True
ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['*']
CORS_ALLOWED_ORIGINS = [
'http://localhost:52330',
]
# Application definition # Application definition
...@@ -39,6 +42,8 @@ INSTALLED_APPS = [ ...@@ -39,6 +42,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'rest_framework', 'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'api', 'api',
'webapp', 'webapp',
...@@ -48,6 +53,7 @@ INSTALLED_APPS = [ ...@@ -48,6 +53,7 @@ INSTALLED_APPS = [
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
...@@ -149,3 +155,14 @@ MEDIA_URL = '/images/' ...@@ -149,3 +155,14 @@ MEDIA_URL = '/images/'
SESSION_COOKIE_AGE = 5 * 60 SESSION_COOKIE_AGE = 5 * 60
# DATE_INPUT_FORMATS = ('%d.%m.%Y',) # 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 ...@@ -2,7 +2,9 @@ from django.contrib import admin
from django.urls import path, include from django.urls import path, include
from django.conf.urls.static import static from django.conf.urls.static import static
from django.conf import settings 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 api import views as api_views
from webapp import views from webapp import views
...@@ -11,6 +13,7 @@ urlpatterns = [ ...@@ -11,6 +13,7 @@ urlpatterns = [
path('', views.IndexRedirectView.as_view(), name='redirect_to_index'), path('', views.IndexRedirectView.as_view(), name='redirect_to_index'),
path('articles/', include('webapp.urls')), path('articles/', include('webapp.urls')),
path('accounts/', include('accounts.urls')), path('accounts/', include('accounts.urls')),
path('api/articles/', api_views.ArticleListView.as_view()), path('api/', include(router.urls)),
path('api/articles/create', api_views.ArticleCreateView.as_view()), 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) ] + 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