Anton
1 year ago
28 changed files with 644 additions and 23 deletions
@ -0,0 +1,131 @@ |
|||||||
|
import requests |
||||||
|
from django.http import HttpResponseRedirect |
||||||
|
from django.utils.html import format_html |
||||||
|
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME |
||||||
|
|
||||||
|
from adminpanelapp.settings import g_telegram_bot_api_token |
||||||
|
from .models import Orders |
||||||
|
|
||||||
|
|
||||||
|
from django.contrib import admin, messages |
||||||
|
from django.urls import reverse |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class OrdersAdmin(admin.ModelAdmin): |
||||||
|
list_display = ('name', 'description', 'time_create', 'adress', 'is_approved', 'orders_photo', 'cheque_image') |
||||||
|
list_editable = ('is_approved',) |
||||||
|
# exclude = ('param_id', 'send_message') |
||||||
|
actions =['change_value_and_redirect',] |
||||||
|
readonly_fields = ['order_photo', 'cheque'] |
||||||
|
|
||||||
|
|
||||||
|
def orders_photo(self, obj): |
||||||
|
if obj.order_photo and obj.order_photo.url: |
||||||
|
return format_html('<img src="{}" width="100" height="100" />', obj.order_photo.url) |
||||||
|
return "-" |
||||||
|
|
||||||
|
|
||||||
|
def cheque_image(self, obj): |
||||||
|
if obj.cheque and obj.cheque.url: |
||||||
|
return format_html('<img src="{}" width="100" height="100" />', obj.cheque.url) |
||||||
|
return "-" |
||||||
|
|
||||||
|
# image_tag.short_description = 'Cheque' |
||||||
|
|
||||||
|
# def photo_link(self, obj): |
||||||
|
# url = obj.get_absolute_url() |
||||||
|
# return format_html('<a href="{}">{}</a>', url, obj.photo_link) |
||||||
|
# |
||||||
|
# photo_link.short_description = 'photo_link' |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# def change_view(self, request, object_id, form_url='', extra_context=None): |
||||||
|
# obj = self.get_object(request, object_id) |
||||||
|
# extra_context = extra_context or {} |
||||||
|
# extra_context['chat_id'] = obj.param_id |
||||||
|
# |
||||||
|
# if obj.send_message: |
||||||
|
# obj.send_message = False |
||||||
|
# obj.save() |
||||||
|
# url = reverse('send_telegram_message') |
||||||
|
# chat_id = obj.param_id |
||||||
|
# url = f"{url}?param_id={chat_id}" |
||||||
|
# print(chat_id) |
||||||
|
# return HttpResponseRedirect(url) |
||||||
|
# |
||||||
|
# |
||||||
|
# return super().change_view(request, object_id, form_url, extra_context) |
||||||
|
|
||||||
|
|
||||||
|
# def change_view(self, request, object_id, form_url='', extra_context=None): |
||||||
|
# obj = self.get_object(request, object_id) |
||||||
|
# if obj.send_message: |
||||||
|
# url = reverse('send_telegram_message') |
||||||
|
# |
||||||
|
# return HttpResponseRedirect(url) |
||||||
|
# |
||||||
|
# return super().change_view(request, object_id, form_url, extra_context) |
||||||
|
|
||||||
|
# def change_value_and_redirect(modeladmin, request, queryset): |
||||||
|
# |
||||||
|
# # Получаем список выбранных объектов |
||||||
|
# selected_objects = request.POST.getlist(ACTION_CHECKBOX_NAME) |
||||||
|
# # Проверяем, что выбран только один объект |
||||||
|
# if len(selected_objects) != 1: |
||||||
|
# # Если выбрано несколько объектов или не выбран ни один, выбрасываем исключение или выводим сообщение пользователю |
||||||
|
# raise ValueError("Выберите только один объект") |
||||||
|
# # Получаем ID выбранного объекта |
||||||
|
# selected_object_id = int(selected_objects[0]) |
||||||
|
# # Получаем объект по ID |
||||||
|
# obj = queryset.get(id=selected_object_id) |
||||||
|
# # Изменяем значение ячейки объекта на False |
||||||
|
# obj.send_message = True |
||||||
|
# obj.save() |
||||||
|
# # Редирект на страницу send_tg_message |
||||||
|
# url = reverse('send_telegram_message') |
||||||
|
# return HttpResponseRedirect(url) |
||||||
|
|
||||||
|
def change_value_and_redirect(modeladmin, request, queryset): |
||||||
|
selected_objects = request.POST.getlist(ACTION_CHECKBOX_NAME) |
||||||
|
if len(selected_objects) != 1: |
||||||
|
messages.error(request, "Выберите только один объект") |
||||||
|
return |
||||||
|
|
||||||
|
selected_chat_id = int(selected_objects[0]) |
||||||
|
obj = queryset.get(id=selected_chat_id) |
||||||
|
chat_id = obj.param_id |
||||||
|
url = reverse('send_telegram_message', kwargs={'chat_id': chat_id}) |
||||||
|
return HttpResponseRedirect(url) |
||||||
|
|
||||||
|
|
||||||
|
change_value_and_redirect.short_description = 'Отправка сообщения' |
||||||
|
|
||||||
|
|
||||||
|
def save_model(self, request, obj, form, change): |
||||||
|
super().save_model(request, obj, form, change) |
||||||
|
|
||||||
|
def send_telegram_message(message): |
||||||
|
bot_token = g_telegram_bot_api_token |
||||||
|
|
||||||
|
chat_id = obj.param_id |
||||||
|
url = f"https://api.telegram.org/bot{bot_token}/sendMessage" |
||||||
|
params = { |
||||||
|
'chat_id': chat_id, |
||||||
|
'text': message |
||||||
|
} |
||||||
|
response = requests.get(url, params=params) |
||||||
|
|
||||||
|
if response.status_code == 200: |
||||||
|
print("Сообщение успешно отправлено!") |
||||||
|
else: |
||||||
|
print("Ошибка при отправке сообщения") |
||||||
|
|
||||||
|
if obj.is_approved == True: |
||||||
|
message2 = 'Ваш заказ принят. Ожидайте получения' |
||||||
|
send_telegram_message(message2) |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
admin.site.register(Orders, OrdersAdmin,) |
@ -0,0 +1,6 @@ |
|||||||
|
from django.apps import AppConfig |
||||||
|
|
||||||
|
|
||||||
|
class AdminpanelConfig(AppConfig): |
||||||
|
default_auto_field = 'django.db.models.BigAutoField' |
||||||
|
name = 'adminpanel' |
@ -0,0 +1,44 @@ |
|||||||
|
from django.db import models |
||||||
|
|
||||||
|
import asyncio |
||||||
|
|
||||||
|
|
||||||
|
class Orders(models.Model): |
||||||
|
SEND_MESSAGE = ( |
||||||
|
(True, 'Написать'), |
||||||
|
(False, 'Не отправлять'), |
||||||
|
(None, 'Неизвестно'), |
||||||
|
) |
||||||
|
|
||||||
|
IS_APPROVED = ( |
||||||
|
(True, 'Заказ подтвержден'), |
||||||
|
(False, 'Заказ не подтвержден'), |
||||||
|
(None, 'Неизвестно'), |
||||||
|
) |
||||||
|
|
||||||
|
param_id = models.CharField(max_length=100, verbose_name='id пользователя в tg', null=True) |
||||||
|
name = models.CharField(max_length=100, verbose_name='наименование', null=True) |
||||||
|
description = models.TextField(verbose_name='описание', null=True) |
||||||
|
order_photo = models.ImageField(upload_to='photo/') |
||||||
|
cheque = models.ImageField(upload_to='photo/') |
||||||
|
adress = models.CharField(max_length=100, verbose_name='адрес доставки', blank=True, null=True) |
||||||
|
time_create = models.DateTimeField(auto_now_add=True, null=True) |
||||||
|
# message = models.CharField(max_length=100, verbose_name='сообщение для пользователя', blank=True, null=True) |
||||||
|
# send_message = models.BooleanField(default=False, verbose_name='отправить сообщение', null=True, choices=SEND_MESSAGE) |
||||||
|
is_approved = models.BooleanField(default=False, verbose_name='подтверждение заказа', null=True, choices=IS_APPROVED) |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class Meta: |
||||||
|
app_label = 'adminpanel' |
||||||
|
verbose_name_plural = 'Заказы' |
||||||
|
|
||||||
|
def __str__(self): |
||||||
|
return self.name |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,6 @@ |
|||||||
|
<form method="post"> |
||||||
|
{% csrf_token %} |
||||||
|
<label for="message">Сообщение:</label> |
||||||
|
<input type="text" id="message" name="message"> |
||||||
|
<button type="submit">Отправить сообщение</button> |
||||||
|
</form> |
@ -0,0 +1,3 @@ |
|||||||
|
from django.test import TestCase |
||||||
|
|
||||||
|
# Create your tests here. |
@ -0,0 +1,7 @@ |
|||||||
|
from django.urls import path, include |
||||||
|
from .views import send_telegram_message |
||||||
|
|
||||||
|
|
||||||
|
urlpatterns = [ |
||||||
|
path('send_telegram_message/<int:chat_id>/', send_telegram_message, name='send_telegram_message'), |
||||||
|
] |
@ -0,0 +1,28 @@ |
|||||||
|
from django.contrib import messages |
||||||
|
from django.http import HttpResponseRedirect |
||||||
|
from django.shortcuts import render, HttpResponse |
||||||
|
import requests |
||||||
|
from django.urls import reverse |
||||||
|
|
||||||
|
from adminpanel.models import Orders |
||||||
|
from bot_sys.config import g_telegram_bot_api_token |
||||||
|
|
||||||
|
|
||||||
|
def send_telegram_message(request, chat_id): |
||||||
|
if request.method == 'POST': |
||||||
|
message = request.POST.get('message') |
||||||
|
|
||||||
|
bot_token = g_telegram_bot_api_token |
||||||
|
url = f'https://api.telegram.org/bot{bot_token}/sendMessage?text={message}&chat_id={chat_id}' |
||||||
|
|
||||||
|
response = requests.get(url) |
||||||
|
if response.status_code == 200: |
||||||
|
messages.success(request, "Сообщение успешно отправлено") |
||||||
|
back_url = reverse('') |
||||||
|
return HttpResponseRedirect(back_url) |
||||||
|
else: |
||||||
|
messages.error(request, "Сообщение не отправлено") |
||||||
|
back_url = reverse('') |
||||||
|
return HttpResponseRedirect(back_url) |
||||||
|
else: |
||||||
|
return render(request, 'send_telegram_message.html') |
@ -1,9 +0,0 @@ |
|||||||
from django.contrib import admin |
|
||||||
from .models import Orders |
|
||||||
|
|
||||||
|
|
||||||
class OrdersAdmin(admin.ModelAdmin): |
|
||||||
list_display = ('name', 'time_create') |
|
||||||
|
|
||||||
|
|
||||||
admin.site.register(Orders, OrdersAdmin,) |
|
@ -1,3 +1,20 @@ |
|||||||
|
import telegram |
||||||
|
from django.http import HttpResponse |
||||||
from django.shortcuts import render |
from django.shortcuts import render |
||||||
|
|
||||||
# Create your views here. |
def send_message(request): |
||||||
|
if request.method == 'POST': |
||||||
|
# Получение данных из POST-запроса |
||||||
|
chat_id = request.POST.get('chat_id') |
||||||
|
message_text = request.POST.get('message_text') |
||||||
|
|
||||||
|
# Создание объекта Telegram Bot |
||||||
|
bot = telegram.Bot(token='YOUR_TELEGRAM_BOT_TOKEN') |
||||||
|
|
||||||
|
# Отправка сообщения |
||||||
|
bot.send_message(chat_id=chat_id, text=message_text) |
||||||
|
|
||||||
|
# Возвращение ответа |
||||||
|
return HttpResponse('Message sent to Telegram.') |
||||||
|
else: |
||||||
|
return render(request, 'send_message.html') |
@ -0,0 +1,16 @@ |
|||||||
|
""" |
||||||
|
ASGI config for adminpanelapp project. |
||||||
|
|
||||||
|
It exposes the ASGI callable as a module-level variable named ``application``. |
||||||
|
|
||||||
|
For more information on this file, see |
||||||
|
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ |
||||||
|
""" |
||||||
|
|
||||||
|
import os |
||||||
|
|
||||||
|
from django.core.asgi import get_asgi_application |
||||||
|
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanelapp.settings') |
||||||
|
|
||||||
|
application = get_asgi_application() |
@ -0,0 +1,135 @@ |
|||||||
|
""" |
||||||
|
Django settings for adminpanelapp project. |
||||||
|
|
||||||
|
Generated by 'django-admin startproject' using Django 4.1.4. |
||||||
|
|
||||||
|
For more information on this file, see |
||||||
|
https://docs.djangoproject.com/en/4.1/topics/settings/ |
||||||
|
|
||||||
|
For the full list of settings and their values, see |
||||||
|
https://docs.djangoproject.com/en/4.1/ref/settings/ |
||||||
|
""" |
||||||
|
import os |
||||||
|
from pathlib import Path |
||||||
|
|
||||||
|
# Build paths inside the project like this: BASE_DIR / 'subdir'. |
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent |
||||||
|
|
||||||
|
|
||||||
|
# Quick-start development settings - unsuitable for production |
||||||
|
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ |
||||||
|
|
||||||
|
# SECURITY WARNING: keep the secret key used in production secret! |
||||||
|
SECRET_KEY = 'django-insecure-11*zwyl6y4w%2j(spzw)+0o8u@frpy++3xk+zoy(!5gg3$1wuf' |
||||||
|
|
||||||
|
# SECURITY WARNING: don't run with debug turned on in production! |
||||||
|
DEBUG = True |
||||||
|
|
||||||
|
ALLOWED_HOSTS = [] |
||||||
|
|
||||||
|
|
||||||
|
# Application definition |
||||||
|
|
||||||
|
INSTALLED_APPS = [ |
||||||
|
'django.contrib.admin', |
||||||
|
'django.contrib.auth', |
||||||
|
'django.contrib.contenttypes', |
||||||
|
'django.contrib.sessions', |
||||||
|
'django.contrib.messages', |
||||||
|
'django.contrib.staticfiles', |
||||||
|
'adminpanel', |
||||||
|
|
||||||
|
|
||||||
|
] |
||||||
|
|
||||||
|
MIDDLEWARE = [ |
||||||
|
'django.middleware.security.SecurityMiddleware', |
||||||
|
'django.contrib.sessions.middleware.SessionMiddleware', |
||||||
|
'django.middleware.common.CommonMiddleware', |
||||||
|
'django.middleware.csrf.CsrfViewMiddleware', |
||||||
|
'django.contrib.auth.middleware.AuthenticationMiddleware', |
||||||
|
'django.contrib.messages.middleware.MessageMiddleware', |
||||||
|
'django.middleware.clickjacking.XFrameOptionsMiddleware', |
||||||
|
] |
||||||
|
|
||||||
|
ROOT_URLCONF = 'adminpanelapp.urls' |
||||||
|
|
||||||
|
TEMPLATES = [ |
||||||
|
{ |
||||||
|
'BACKEND': 'django.template.backends.django.DjangoTemplates', |
||||||
|
'DIRS': [], |
||||||
|
'APP_DIRS': True, |
||||||
|
'OPTIONS': { |
||||||
|
'context_processors': [ |
||||||
|
'django.template.context_processors.debug', |
||||||
|
'django.template.context_processors.request', |
||||||
|
'django.contrib.auth.context_processors.auth', |
||||||
|
'django.contrib.messages.context_processors.messages', |
||||||
|
], |
||||||
|
}, |
||||||
|
}, |
||||||
|
] |
||||||
|
|
||||||
|
WSGI_APPLICATION = 'adminpanelapp.wsgi.application' |
||||||
|
|
||||||
|
|
||||||
|
# Database |
||||||
|
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases |
||||||
|
|
||||||
|
DATABASES = { |
||||||
|
'default': { |
||||||
|
'ENGINE': 'django.db.backends.sqlite3', |
||||||
|
'NAME': BASE_DIR / 'db.sqlite3', |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
# Password validation |
||||||
|
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators |
||||||
|
|
||||||
|
AUTH_PASSWORD_VALIDATORS = [ |
||||||
|
{ |
||||||
|
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', |
||||||
|
}, |
||||||
|
{ |
||||||
|
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', |
||||||
|
}, |
||||||
|
{ |
||||||
|
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', |
||||||
|
}, |
||||||
|
{ |
||||||
|
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', |
||||||
|
}, |
||||||
|
] |
||||||
|
|
||||||
|
|
||||||
|
# Internationalization |
||||||
|
# https://docs.djangoproject.com/en/4.1/topics/i18n/ |
||||||
|
|
||||||
|
LANGUAGE_CODE = 'en-us' |
||||||
|
|
||||||
|
TIME_ZONE = 'UTC' |
||||||
|
|
||||||
|
USE_I18N = True |
||||||
|
|
||||||
|
USE_TZ = True |
||||||
|
|
||||||
|
|
||||||
|
# Static files (CSS, JavaScript, Images) |
||||||
|
# https://docs.djangoproject.com/en/4.1/howto/static-files/ |
||||||
|
|
||||||
|
STATIC_URL = 'static/' |
||||||
|
|
||||||
|
# Default primary key field type |
||||||
|
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field |
||||||
|
|
||||||
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' |
||||||
|
|
||||||
|
ASGI_APPLICATION = 'adminpanelapp.asgi.application' |
||||||
|
ASYNC_MODE = 'django' |
||||||
|
g_telegram_bot_api_token = '6212211018:AAEwcEN0NdjbhqDiClUk8vZkE_vfRUxsReU' |
||||||
|
|
||||||
|
|
||||||
|
MEDIA_URL = '/media/' |
||||||
|
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') |
||||||
|
|
@ -0,0 +1,15 @@ |
|||||||
|
from django.contrib import admin |
||||||
|
from django.urls import path, include |
||||||
|
from django.views.generic import RedirectView |
||||||
|
from django.conf import settings |
||||||
|
from django.conf.urls.static import static |
||||||
|
|
||||||
|
urlpatterns = [ |
||||||
|
path('admin/', admin.site.urls), |
||||||
|
path('', include('adminpanel.urls')), |
||||||
|
path('', RedirectView.as_view(url='/admin/adminpanel/orders'), name='') |
||||||
|
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,16 @@ |
|||||||
|
""" |
||||||
|
WSGI config for adminpanelapp project. |
||||||
|
|
||||||
|
It exposes the WSGI callable as a module-level variable named ``application``. |
||||||
|
|
||||||
|
For more information on this file, see |
||||||
|
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ |
||||||
|
""" |
||||||
|
|
||||||
|
import os |
||||||
|
|
||||||
|
from django.core.wsgi import get_wsgi_application |
||||||
|
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanelapp.settings') |
||||||
|
|
||||||
|
application = get_wsgi_application() |
@ -0,0 +1,22 @@ |
|||||||
|
#!/usr/bin/env python |
||||||
|
"""Django's command-line utility for administrative tasks.""" |
||||||
|
import os |
||||||
|
import sys |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
"""Run administrative tasks.""" |
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanelapp.settings') |
||||||
|
try: |
||||||
|
from django.core.management import execute_from_command_line |
||||||
|
except ImportError as exc: |
||||||
|
raise ImportError( |
||||||
|
"Couldn't import Django. Are you sure it's installed and " |
||||||
|
"available on your PYTHONPATH environment variable? Did you " |
||||||
|
"forget to activate a virtual environment?" |
||||||
|
) from exc |
||||||
|
execute_from_command_line(sys.argv) |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': |
||||||
|
main() |
Loading…
Reference in new issue