Compare commits

...

5 Commits

  1. 10
      adminpanel/settings.py
  2. 3
      adminpanel/urls.py
  3. 66
      adminpanelapp/admin.py
  4. 26
      adminpanelapp/models.py
  5. 33
      adminpanelapp/templates/send_telegram_message.html
  6. 11
      adminpanelapp/views.py
  7. 5
      bot_sys/config.py
  8. 4
      requirements.txt

10
adminpanel/settings.py

@ -24,13 +24,14 @@ load_dotenv()
SECRET_KEY = os.getenv('PLATFORM_ADMINPANEL_SECRET_KEY') SECRET_KEY = os.getenv('PLATFORM_ADMINPANEL_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False DEBUG = True
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['*']
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'django_admin_listfilter_dropdown',
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.contenttypes',
@ -38,7 +39,7 @@ INSTALLED_APPS = [
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'adminpanelapp', 'adminpanelapp',
'rangefilter',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -115,7 +116,7 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/ # https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/' STATIC_URL = '/static/'
# Default primary key field type # Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
@ -123,4 +124,5 @@ STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
ASGI_APPLICATION = 'adminpanelapp.asgi.application' ASGI_APPLICATION = 'adminpanelapp.asgi.application'
ASYNC_MODE = 'django' ASYNC_MODE = 'django'

3
adminpanel/urls.py

@ -1,8 +1,7 @@
from django.contrib import admin from django.contrib import admin
from django.urls import path, include from django.urls import path, include
from django.views.generic import RedirectView from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),

66
adminpanelapp/admin.py

@ -1,15 +1,51 @@
from datetime import timedelta, datetime
from django.contrib.auth.models import User, Group
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from .models import Orders from django_admin_listfilter_dropdown.filters import DropdownFilter
from .models import Orders, Users
from django.contrib import admin, messages from django.contrib import admin, messages
from django.urls import reverse from django.urls import reverse
from rangefilter.filters import DateRangeFilter
class OrdersAdmin(admin.ModelAdmin): class OrdersAdmin(admin.ModelAdmin):
list_display = ('orderName', 'orderCreateDateTime', 'orderDesc', 'orderAddress', 'show_photo', 'show_photopay')
actions =['send_message'] list_display = (
'orderName', 'orderCreateDateTime', 'orderDesc', 'orderAddress',
'catID', 'userName', 'orderStatus', 'show_photo', 'show_photopay',
)
actions = ['send_message']
exclude = ['orderAccess', 'userID', 'orderPhoto', 'orderPhotoPay'] exclude = ['orderAccess', 'userID', 'orderPhoto', 'orderPhotoPay']
search_fields = ['orderName__regex', 'orderCreateDateTime__regex', 'orderDesc__regex',
'orderAddress__regex', 'catID__regex', 'orderStatus__regex'
]
list_filter = [
('orderName', DropdownFilter),
('orderAddress', DropdownFilter),
('orderDesc', DropdownFilter),
('catID', DropdownFilter),
('orderStatus', DropdownFilter),
('orderCreateDateTime', DateRangeFilter),
]
def userName(self, obj):
user = Users.objects.get(user_id=obj.userID)
return user.userName
def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['show_delete'] = False
extra_context['show_save'] = False
extra_context['show_save_and_continue'] = False
return super().changeform_view(request, object_id, form_url, extra_context)
def has_add_permission(self, request):
return False
def show_photo(self, obj): def show_photo(self, obj):
html = obj.get_photo_html() html = obj.get_photo_html()
@ -37,4 +73,26 @@ class OrdersAdmin(admin.ModelAdmin):
send_message.short_description = 'Отправка сообщения' send_message.short_description = 'Отправка сообщения'
class CustomUserAdmin(admin.ModelAdmin):
# Переопределение метода, чтобы запретить добавление пользователей
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
def has_view_or_change_permission(self, request, obj=None):
return False
class CustomGroupAdmin(admin.ModelAdmin):
#Переопределение метода, чтобы запретить добавление групп
def has_add_permission(self, request):
return False
admin.site.unregister(User) # Снятие регистрации стандартного класса администратора пользователей
admin.site.unregister(Group) # Снятие регистрации стандартного класса администратора групп
admin.site.register(User, CustomUserAdmin) # Регистрация настроенного класса администратора пользователей
admin.site.register(Group, CustomGroupAdmin) # Регистрация настроенного класса администратора групп
admin.site.register(Orders, OrdersAdmin) admin.site.register(Orders, OrdersAdmin)

26
adminpanelapp/models.py

@ -1,11 +1,26 @@
import time
from urllib.parse import quote from urllib.parse import quote
import requests import requests
from django.db import models from django.db import models
from bot_sys.config import GetTelegramBotApiToken from bot_sys.config import GetTelegramBotApiToken
class Users(models.Model):
user_id = models.CharField(max_length=100, primary_key=True)
userName = models.CharField(max_length=100, verbose_name='Имя пользователя')
userFirstName = models.CharField(max_length=100, verbose_name='Имя')
userLastName = models.CharField(max_length=100, verbose_name='Фамилия')
userIsBot = models.BooleanField(verbose_name='Является ботом')
userLanguageCode = models.CharField(max_length=100, verbose_name='Код языка')
userPhoto = models.ImageField(verbose_name='Фото пользователя')
userAccess = models.CharField(max_length=100, verbose_name='Доступ')
createDateTime = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время создания')
class Meta:
verbose_name_plural = 'Заказы'
managed = False
db_table = 'users'
class Orders(models.Model): class Orders(models.Model):
orderID = models.AutoField(primary_key=True, verbose_name='id заказа') orderID = models.AutoField(primary_key=True, verbose_name='id заказа')
userID = models.CharField(max_length=100, verbose_name='id пользователя в tg', null=True) userID = models.CharField(max_length=100, verbose_name='id пользователя в tg', null=True)
@ -17,6 +32,7 @@ class Orders(models.Model):
orderAccess = models.CharField(max_length=100, verbose_name='доступ', blank=True, null=True) orderAccess = models.CharField(max_length=100, verbose_name='доступ', blank=True, null=True)
orderCreateDateTime = models.DateTimeField(auto_now_add=True, null=True, verbose_name='дата и время создания') orderCreateDateTime = models.DateTimeField(auto_now_add=True, null=True, verbose_name='дата и время создания')
orderStatus = models.CharField(max_length=100, verbose_name='статус заказа', blank=True, null=True) orderStatus = models.CharField(max_length=100, verbose_name='статус заказа', blank=True, null=True)
catID = models.CharField(max_length=100, verbose_name='категория', blank=True, null=True)
def get_photo_html(self, width=100, height=100, large_width=400, large_height=400): def get_photo_html(self, width=100, height=100, large_width=400, large_height=400):
file_id = self.orderPhoto file_id = self.orderPhoto
@ -139,4 +155,6 @@ class Orders(models.Model):
verbose_name_plural = 'Заказы' verbose_name_plural = 'Заказы'
managed = False managed = False
db_table = 'orders' db_table = 'orders'

33
adminpanelapp/templates/send_telegram_message.html

@ -1,8 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<title>Отправка сообщений</title>
</head>
<body>
<form method="post"> <form method="post">
{% csrf_token %} {% csrf_token %}
<div><label for="message">Сообщение:</label></div> <div>
<div><pre> <label for="message">Сообщение:</label>
<textarea id="message" name="message" cols="50" rows="10" placeholder="Введите сообщение"></textarea> </div>
</pre></div> <div>
<div><button type="submit">Отправить сообщение</button></div> <textarea id="message" name="message" cols="50" rows="10" placeholder="Введите сообщение" class="markdownx"></textarea>
</form> </div>
<div>
<button type="submit">Отправить сообщение</button>
</div>
</form>
<p>
Пример разметки<br>
<br>
<strong>• *Жирный текст* </strong><br>
<code>• `номер карты` При нажатии пользователем на текст, заключенный в ``, автоматически копируется</code><br>
<i>• _курсив_</i><br>
</p>
</body>
</html>

11
adminpanelapp/views.py

@ -10,9 +10,16 @@ def send_telegram_message(request, chat_id):
message = request.POST.get('message') message = request.POST.get('message')
bot_token = GetTelegramBotApiToken() bot_token = GetTelegramBotApiToken()
url = f'https://api.telegram.org/bot{bot_token}/sendMessage?text={message}&chat_id={chat_id}' url = f'https://api.telegram.org/bot{bot_token}/sendMessage'
payload = {
'chat_id': chat_id,
'text': message,
'parse_mode': 'markdown'
}
response = requests.post(url, json=payload)
response = requests.get(url)
if response.status_code == 200: if response.status_code == 200:
messages.success(request, "Сообщение успешно отправлено") messages.success(request, "Сообщение успешно отправлено")
back_url = reverse('') back_url = reverse('')

5
bot_sys/config.py

@ -1,7 +1,7 @@
#-*-coding utf-8-*- #-*-coding utf-8-*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru> # Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Настнойка основных параметров системы # Настройка основных параметров системы
# --------------------------------------------------------- # ---------------------------------------------------------
# API токен телеграмм бота. Создаётся с помощью @BotFather # API токен телеграмм бота. Создаётся с помощью @BotFather
@ -57,5 +57,4 @@ def GetRootIDs():
for i in root_ids: for i in root_ids:
g_root_ids += [ClearReadLine(i)] g_root_ids += [ClearReadLine(i)]
return g_root_ids return g_root_ids

4
requirements.txt

@ -4,4 +4,6 @@ weasyprint
Django==2.2.1 Django==2.2.1
python-dotenv==0.21.1 python-dotenv==0.21.1
requests==2.31.0 requests==2.31.0
urllib3==1.25.11 urllib3==1.25.11
django-admin-list-filter-dropdown==1.0.3
django-admin-rangefilter==0.11.2
Loading…
Cancel
Save