chore: первый апдейт
This commit is contained in:
1 parent
a53fffdb59
commit
136894a376
11 files changed
+183
-11
No files matched your search
@@ -1,3 +1,6 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.venv/
|
.venv/
|
||||||
extra/
|
extra/
|
||||||
|
src/db.sqlite3
|
||||||
|
src/design/static_root/
|
||||||
|
__pycache__/
|
||||||
@@ -1,3 +1,16 @@
|
|||||||
# TODO: добавить make команды для создания и применения миграций, создания супер пользователя и запуск тестового сервера
|
.PHONY: dj_makemigrations dj_migrate dj_superuser dj_run dj_test
|
||||||
|
|
||||||
dj_makemigrations:
|
dj_makemigrations:
|
||||||
cd src/ && ./manage.py makemigrations
|
cd src/ && ./manage.py makemigrations
|
||||||
|
|
||||||
|
dj_migrate:
|
||||||
|
cd src/ && ./manage.py migrate
|
||||||
|
|
||||||
|
dj_superuser:
|
||||||
|
cd src/ && ./manage.py createsuperuser
|
||||||
|
|
||||||
|
dj_run:
|
||||||
|
cd src/ && ./manage.py runserver
|
||||||
|
|
||||||
|
dj_test:
|
||||||
|
cd src/ && ./manage.py test
|
||||||
+13
-3
@@ -1,6 +1,16 @@
|
|||||||
services:
|
services:
|
||||||
xui:
|
xui:
|
||||||
# TODO: настроить поднятие сервиса 3x-ui для тестирования api
|
# 3x-ui для тестирования api. Панель: http://127.0.0.1:2053 (по умолчанию admin/admin)
|
||||||
|
image: ghcr.io/mhsanaei/3x-ui:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
XRAY_VMESS_AEAD_FORCED: "false"
|
||||||
|
XUI_ENABLE_FAIL2BAN: "false"
|
||||||
|
ports:
|
||||||
|
- "2053:2053"
|
||||||
|
volumes:
|
||||||
|
- ./extra/xui/db/:/etc/x-ui/
|
||||||
|
- ./extra/xui/cert/:/root/cert/
|
||||||
|
|
||||||
telegram:
|
# telegram:
|
||||||
# TODO: настроить старт телеграм сервиса предоставляемый pyTelegramBotAPI
|
# # TODO: настроить старт телеграм сервиса предоставляемый pyTelegramBotAPI
|
||||||
+1
-1
@@ -2,4 +2,4 @@
|
|||||||
|
|
||||||
Django приложение связывающее все части сайта в одном месте. Никто не импортирует App, кроме MyPointVPN, а App может импортировать все.
|
Django приложение связывающее все части сайта в одном месте. Никто не импортирует App, кроме MyPointVPN, а App может импортировать все.
|
||||||
|
|
||||||
-[ ] Реализует кастомный менеджер модели и кастомную модель пользователя с отключенным email.
|
- [x] Реализует кастомный менеджер модели и кастомную модель пользователя с отключенным email.
|
||||||
+30
-1
@@ -1 +1,30 @@
|
|||||||
# Register your models here.
|
from django.contrib import admin
|
||||||
|
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
|
||||||
|
from django.contrib.auth.forms import AdminUserCreationForm, UserChangeForm
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
from .models import User
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreationForm(AdminUserCreationForm):
|
||||||
|
class Meta(AdminUserCreationForm.Meta):
|
||||||
|
model = User
|
||||||
|
|
||||||
|
|
||||||
|
class UserEditForm(UserChangeForm):
|
||||||
|
class Meta(UserChangeForm.Meta):
|
||||||
|
model = User
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(User)
|
||||||
|
class UserAdmin(BaseUserAdmin):
|
||||||
|
form = UserEditForm
|
||||||
|
add_form = UserCreationForm
|
||||||
|
fieldsets = (
|
||||||
|
(None, {'fields': ('username', 'password')}),
|
||||||
|
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
|
||||||
|
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
|
||||||
|
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
|
||||||
|
)
|
||||||
|
list_display = ('username', 'first_name', 'last_name', 'is_staff')
|
||||||
|
search_fields = ('username', 'first_name', 'last_name')
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Generated by Django 6.1.1 on 2026-09-23 20:50
|
||||||
|
|
||||||
|
import App.models
|
||||||
|
import django.contrib.auth.validators
|
||||||
|
import django.utils.timezone
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('auth', '0012_alter_user_first_name_max_length'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='User',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('password', models.CharField(max_length=128, verbose_name='password')),
|
||||||
|
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
|
||||||
|
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
|
||||||
|
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
|
||||||
|
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
|
||||||
|
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
|
||||||
|
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
|
||||||
|
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
|
||||||
|
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
|
||||||
|
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
|
||||||
|
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'user',
|
||||||
|
'verbose_name_plural': 'users',
|
||||||
|
'abstract': False,
|
||||||
|
},
|
||||||
|
managers=[
|
||||||
|
('objects', App.models.UserManager()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
+48
-2
@@ -1,2 +1,48 @@
|
|||||||
# Create your models here.
|
from django.contrib.auth.base_user import BaseUserManager
|
||||||
# TODO: создать менеджер модель пользователя и кастомную модель пользователя в которой уберем поле email и позволим регистрироваться только по username и password
|
from django.contrib.auth.models import AbstractUser
|
||||||
|
|
||||||
|
|
||||||
|
class UserManager(BaseUserManager):
|
||||||
|
"""Менеджер пользователей без email: только username и password."""
|
||||||
|
|
||||||
|
use_in_migrations = True
|
||||||
|
|
||||||
|
def _create_user(self, username, password, **extra_fields):
|
||||||
|
if not username:
|
||||||
|
raise ValueError('The given username must be set')
|
||||||
|
username = self.model.normalize_username(username)
|
||||||
|
user = self.model(username=username, **extra_fields)
|
||||||
|
user.set_password(password)
|
||||||
|
user.save(using=self._db)
|
||||||
|
return user
|
||||||
|
|
||||||
|
def create_user(self, username, password=None, **extra_fields):
|
||||||
|
extra_fields.setdefault('is_staff', False)
|
||||||
|
extra_fields.setdefault('is_superuser', False)
|
||||||
|
return self._create_user(username, password, **extra_fields)
|
||||||
|
|
||||||
|
def create_superuser(self, username, 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(username, password, **extra_fields)
|
||||||
|
|
||||||
|
|
||||||
|
class User(AbstractUser):
|
||||||
|
"""Пользователь без email. Регистрация только по username и password."""
|
||||||
|
|
||||||
|
email = None
|
||||||
|
EMAIL_FIELD = None
|
||||||
|
REQUIRED_FIELDS = []
|
||||||
|
|
||||||
|
objects = UserManager()
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
# AbstractUser.clean() нормализует email, которого у нас нет
|
||||||
|
pass
|
||||||
|
|
||||||
|
def email_user(self, *args, **kwargs):
|
||||||
|
raise NotImplementedError('User has no email')
|
||||||
+27
-1
@@ -1 +1,27 @@
|
|||||||
# Create your tests here.
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
|
||||||
|
class UserModelTests(TestCase):
|
||||||
|
def test_create_user_without_email(self):
|
||||||
|
user = get_user_model().objects.create_user('alice', 'secret-pass-123')
|
||||||
|
self.assertEqual(user.username, 'alice')
|
||||||
|
self.assertTrue(user.check_password('secret-pass-123'))
|
||||||
|
self.assertFalse(user.is_staff)
|
||||||
|
self.assertFalse(user.is_superuser)
|
||||||
|
self.assertFalse(hasattr(user, 'email') and user.email)
|
||||||
|
|
||||||
|
def test_create_superuser(self):
|
||||||
|
user = get_user_model().objects.create_superuser('root', 'secret-pass-123')
|
||||||
|
self.assertTrue(user.is_staff)
|
||||||
|
self.assertTrue(user.is_superuser)
|
||||||
|
|
||||||
|
def test_username_required(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
get_user_model().objects.create_user('', 'secret-pass-123')
|
||||||
|
|
||||||
|
def test_admin_add_user_page(self):
|
||||||
|
admin = get_user_model().objects.create_superuser('root', 'secret-pass-123')
|
||||||
|
self.client.force_login(admin)
|
||||||
|
self.assertEqual(self.client.get('/admin/App/user/add/').status_code, 200)
|
||||||
|
self.assertEqual(self.client.get(f'/admin/App/user/{admin.pk}/change/').status_code, 200)
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
- `base.py` - базовые настройки Django - нельзя редактировать
|
- `base.py` - базовые настройки Django - нельзя редактировать
|
||||||
- `project.py` - настройки проекта - все параметры проекта, которые он заводит и определяет живут тут
|
- `project.py` - настройки проекта - все параметры проекта, которые он заводит и определяет живут тут
|
||||||
|
|
||||||
Допустимо создавать свои файлы настроек, и первой строкой следует импортировать `prokect.py`.
|
Допустимо создавать свои файлы настроек, и первой строкой следует импортировать `project.py`.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from .project import *
|
from .project import *
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
from .base import *
|
from .project import *
|
||||||
@@ -11,3 +11,5 @@ STATIC_ROOT = BASE_DIR / 'design/static_root'
|
|||||||
MEDIA_ROOT = BASE_DIR.parent / 'extra/media'
|
MEDIA_ROOT = BASE_DIR.parent / 'extra/media'
|
||||||
|
|
||||||
MEDIA_URL = '/media/'
|
MEDIA_URL = '/media/'
|
||||||
|
|
||||||
|
AUTH_USER_MODEL = 'App.User'
|
||||||
Reference in new issue
Block a user