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 web.models import StatusChoices, Article, Comment
from web.models import Article, Comment
class ArticleSerializer(serializers.ModelSerializer):
......@@ -47,7 +48,38 @@ class ArticleGetSerializer(serializers.ModelSerializer):
'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 Meta:
# model = Comment
......
......@@ -11,4 +11,5 @@ router.register('article', views.ArticleViewSet)
urlpatterns = [
path('', include(router.urls)),
path('login', obtain_auth_token),
path('register', views.UserAPIView.as_view())
]
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
......@@ -13,13 +15,10 @@ class ArticleViewSet(ModelViewSet):
'get': serializers.ArticleGetSerializer,
'patch': serializers.ArticlePartialUpdateSerializer,
}
permission_classes = (
permissions.AllowAny,
permissions.IsAdminUser,
permissions.IsAuthenticatedOrReadOnly,
permissions.DjangoModelPermissions,
permissions.DjangoModelPermissionsOrAnonReadOnly,
)
@decorators.action(methods=['GET'], detail=True)
def hello(self, request, *args, **kwargs):
return Response({'msg': 'Hello World!'})
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
......@@ -32,3 +31,11 @@ class ArticleViewSet(ModelViewSet):
return self.method_serializers.get(method)
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) {
event.preventDefault()
let token
let userResp = {
"username": "joh2ndoe",
"first_name": "john",
"last_name": "doe",
"email": "johndoe@gmail.com",
"password": "rootroot"
}
localStorage.setItem('currentUser', userResp)
await $.ajax({
url: '/api/login',
......@@ -11,12 +20,12 @@ $('#articlesMain').on('click', async function (event) {
data: JSON.stringify({username: 'admin', password: 'root'}),
contentType: 'application/json'
})
.then(function (resp) {token = resp.token})
.then(function (resp) {localStorage.setItem('token', resp.token)})
await $.ajax({
url: '/api/article',
method: 'get',
headers: {Authorization: 'Token ' + token}
headers: {Authorization: 'Token ' + localStorage.getItem('token')}
}).then(resp => console.log(resp))
})
......@@ -160,7 +160,7 @@ REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
# 'DEFAULT_PERMISSION_CLASSES': (
# '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