-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
242dabe
commit e813095
Showing
11 changed files
with
157 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
from django.contrib import admin | ||
from custom_user.models import CustomUser | ||
|
||
|
||
@admin.register(CustomUser) | ||
class UserAdmin(admin.ModelAdmin): | ||
list_display = ('email', 'phone', 'is_seller', 'is_active', ) | ||
list_display_links = ('email', ) | ||
list_editable = ('is_seller', 'is_active', ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class CustomUserConfig(AppConfig): | ||
default_auto_field = 'django.db.models.BigAutoField' | ||
name = 'custom_user' | ||
verbose_name = 'Зарегистрированные пользователи' |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
from django.contrib.auth.models import AbstractUser | ||
from django.db import models | ||
from custom_user.user_manager import CustomUserManager | ||
|
||
|
||
NULLABLE = {'blank': True, 'null': True} | ||
|
||
|
||
class CustomUser(AbstractUser): | ||
""" | ||
Расширение стандартной модели пользователя в соответствии с требованиями текущего проекта. | ||
""" | ||
|
||
class VisitorStatus(models.IntegerChoices): | ||
""" | ||
Вспомогательный класс для определения статуса посетителя магазина. | ||
По умолчанию, каждый новый пользователь имеет статус 'Посетитель'. | ||
""" | ||
|
||
COMMON_USER = 0, "Посетитель" | ||
SELLER = 1, "Продавец" | ||
|
||
username = None | ||
|
||
email = models.EmailField(unique=True, verbose_name='Email') | ||
|
||
phone = models.CharField(max_length=20, verbose_name='Телефон', **NULLABLE) | ||
|
||
is_seller = models.BooleanField(choices=VisitorStatus.choices, default=VisitorStatus.COMMON_USER, | ||
verbose_name='Статус посетителя') | ||
|
||
is_active = models.BooleanField(default=True, verbose_name='Статус активации') | ||
|
||
objects = CustomUserManager() | ||
|
||
USERNAME_FIELD = "email" | ||
REQUIRED_FIELDS = [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from rest_framework import serializers | ||
from custom_user.models import CustomUser | ||
|
||
|
||
class CustomUserListSerializer(serializers.ModelSerializer): | ||
""" | ||
Сериализатор модели CustomUser. | ||
Используется при вызове GET запросов в контроллере CustomUserListView | ||
""" | ||
|
||
class Meta: | ||
model = CustomUser | ||
fields = '__all__' | ||
|
||
|
||
class CustomUserCreateSerializer(serializers.ModelSerializer): | ||
""" | ||
Сериализатор модели CustomUser. | ||
Используется при вызове GET запросов в контроллере CustomUserCreateView | ||
""" | ||
|
||
class Meta: | ||
model = CustomUser | ||
fields = ('password', 'email', ) | ||
|
||
def create(self, validated_data): | ||
""" | ||
:param validated_data: Данные, переданные при создании нового пользователя | ||
Метод переопределен для корректного создания нового пользователя. | ||
Пароль указанный при создании пользователя хэшируется, появляется возможность авторизации по JWT. | ||
:return: Создается новый экземпляр класса CustomUser | ||
""" | ||
|
||
new_custom_user = CustomUser.objects.create_user(**validated_data) | ||
return new_custom_user |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from django.urls import path | ||
from .apps import CustomUserConfig | ||
from .views import CustomUserListView, CustomUserCreateView | ||
|
||
|
||
app_name = CustomUserConfig.name | ||
|
||
|
||
urlpatterns = [ | ||
path('', CustomUserListView.as_view(), name='custom_user_list'), | ||
path('create/', CustomUserCreateView.as_view(), name='custom_user_create') | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
from django.apps import apps | ||
from django.contrib.auth.hashers import make_password | ||
from django.contrib.auth.models import UserManager | ||
|
||
|
||
class CustomUserManager(UserManager): | ||
use_in_migrations = True | ||
|
||
def _create_user(self, email, password, **extra_fields): | ||
""" | ||
Create and save a user with the given username, email, and password. | ||
""" | ||
|
||
email = self.normalize_email(email) | ||
|
||
GlobalUserModel = apps.get_model( | ||
self.model._meta.app_label, self.model._meta.object_name | ||
) | ||
user = self.model(email=email, **extra_fields) | ||
user.password = make_password(password) | ||
user.save(using=self._db) | ||
return user | ||
|
||
def create_user(self, email=None, password=None, **extra_fields): | ||
extra_fields.setdefault("is_staff", False) | ||
extra_fields.setdefault("is_superuser", False) | ||
return self._create_user(email, password, **extra_fields) | ||
|
||
def create_superuser(self, email=None, password=None, **extra_fields): | ||
extra_fields.setdefault("is_staff", True) | ||
extra_fields.setdefault("is_superuser", True) | ||
|
||
if extra_fields.get("is_staff") is not True: | ||
raise ValueError("Superuser must have is_staff=True.") | ||
if extra_fields.get("is_superuser") is not True: | ||
raise ValueError("Superuser must have is_superuser=True.") | ||
|
||
return self._create_user(email, password, **extra_fields) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
from rest_framework import generics | ||
from custom_user.models import CustomUser | ||
from custom_user.serializers import CustomUserListSerializer, CustomUserCreateSerializer | ||
|
||
|
||
class CustomUserListView(generics.ListAPIView): | ||
"""Контроллер для отображения списка зарегистрированных пользователей""" | ||
|
||
serializer_class = CustomUserListSerializer | ||
queryset = CustomUser.objects.all() | ||
|
||
|
||
class CustomUserCreateView(generics.CreateAPIView): | ||
"""Контроллер для регистрации новых пользователей""" | ||
|
||
queryset = CustomUser.objects.all() | ||
serializer_class = CustomUserCreateSerializer |