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

lesson 72

parent 89cd7948
from rest_framework import generics
class MethodSerializerMixin:
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
class RetrieveCreateAPIView(MethodSerializerMixin,
generics.CreateAPIView,
generics.RetrieveAPIView,):
pass
from rest_framework import serializers from rest_framework import serializers, exceptions
from django.contrib.auth import get_user_model
from accounts.models import User from accounts.models import User
from web.models import StatusChoices, Article, Comment from web.models import Article, Comment
class ArticleSerializer(serializers.ModelSerializer): class ArticleSerializer(serializers.ModelSerializer):
...@@ -47,7 +48,38 @@ class ArticleGetSerializer(serializers.ModelSerializer): ...@@ -47,7 +48,38 @@ class ArticleGetSerializer(serializers.ModelSerializer):
'created_at', 'updated_at', 'created_at', 'updated_at',
] ]
#
class UserGetSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = [
'id', 'username', 'first_name',
'last_name', 'email'
]
class UserCreateSerializer(serializers.ModelSerializer):
password_confirm = serializers.CharField(max_length=200, required=True, write_only=True)
class Meta:
model = get_user_model()
fields = [
'username', 'first_name', 'last_name',
'email', 'password', 'password_confirm'
]
def clean(self, values):
password, password_confirm = (v for v in values if v in ['password', 'password_confirm'])
if password != password_confirm:
raise exceptions.ValidationError('passwords not match', code=400)
return values
def create(self, validated_data):
validated_data.pop('password_confirm')
return super().create(validated_data)
# class CommentsCreateSerializer(serializers.ModelSerializer): # class CommentsCreateSerializer(serializers.ModelSerializer):
# class Meta: # class Meta:
# model = Comment # model = Comment
......
...@@ -11,4 +11,5 @@ router.register('article', views.ArticleViewSet) ...@@ -11,4 +11,5 @@ router.register('article', views.ArticleViewSet)
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path('', include(router.urls)),
path('login', obtain_auth_token), path('login', obtain_auth_token),
path('register', views.UserAPIView.as_view())
] ]
from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions from rest_framework import permissions, decorators
from django.contrib.auth import get_user_model
from rest_framework.response import Response
from api import serializers from api import serializers, generics
from web.models import Article from web.models import Article
...@@ -13,13 +15,10 @@ class ArticleViewSet(ModelViewSet): ...@@ -13,13 +15,10 @@ class ArticleViewSet(ModelViewSet):
'get': serializers.ArticleGetSerializer, 'get': serializers.ArticleGetSerializer,
'patch': serializers.ArticlePartialUpdateSerializer, 'patch': serializers.ArticlePartialUpdateSerializer,
} }
permission_classes = (
permissions.AllowAny, @decorators.action(methods=['GET'], detail=True)
permissions.IsAdminUser, def hello(self, request, *args, **kwargs):
permissions.IsAuthenticatedOrReadOnly, return Response({'msg': 'Hello World!'})
permissions.DjangoModelPermissions,
permissions.DjangoModelPermissionsOrAnonReadOnly,
)
def get_permissions(self): def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS: if self.request.method in permissions.SAFE_METHODS:
...@@ -32,3 +31,11 @@ class ArticleViewSet(ModelViewSet): ...@@ -32,3 +31,11 @@ class ArticleViewSet(ModelViewSet):
return self.method_serializers.get(method) return self.method_serializers.get(method)
return self.serializer_class return self.serializer_class
class UserAPIView(generics.RetrieveCreateAPIView):
queryset = get_user_model().objects.all()
method_serializers = {
'get': serializers.UserGetSerializer,
'post': serializers.UserCreateSerializer,
}
...@@ -4,6 +4,15 @@ $('#articlesMain').on('click', async function (event) { ...@@ -4,6 +4,15 @@ $('#articlesMain').on('click', async function (event) {
event.preventDefault() event.preventDefault()
let token let token
let userResp = {
"username": "joh2ndoe",
"first_name": "john",
"last_name": "doe",
"email": "johndoe@gmail.com",
"password": "rootroot"
}
localStorage.setItem('currentUser', userResp)
await $.ajax({ await $.ajax({
url: '/api/login', url: '/api/login',
...@@ -11,12 +20,12 @@ $('#articlesMain').on('click', async function (event) { ...@@ -11,12 +20,12 @@ $('#articlesMain').on('click', async function (event) {
data: JSON.stringify({username: 'admin', password: 'root'}), data: JSON.stringify({username: 'admin', password: 'root'}),
contentType: 'application/json' contentType: 'application/json'
}) })
.then(function (resp) {token = resp.token}) .then(function (resp) {localStorage.setItem('token', resp.token)})
await $.ajax({ await $.ajax({
url: '/api/article', url: '/api/article',
method: 'get', method: 'get',
headers: {Authorization: 'Token ' + token} headers: {Authorization: 'Token ' + localStorage.getItem('token')}
}).then(resp => console.log(resp)) }).then(resp => console.log(resp))
}) })
...@@ -160,7 +160,7 @@ REST_FRAMEWORK = { ...@@ -160,7 +160,7 @@ REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ( 'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication',
), ),
'DEFAULT_PERMISSION_CLASSES': ( # 'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.IsAuthenticated',
) # )
} }
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