From e5d940e3c95fe262348691f3d514c421ad26255c Mon Sep 17 00:00:00 2001 From: Parsa Nazer Date: Tue, 12 May 2026 09:47:45 +0330 Subject: [PATCH] update prints to log --- backend/account/models.py | 14 ++++++++------ backend/chat/models.py | 5 ++++- backend/core/views.py | 9 +++++---- backend/order/admin.py | 6 ++++-- backend/order/models.py | 15 ++++++++------- backend/order/tasks.py | 6 +++--- backend/order/views.py | 4 ++-- backend/product/admin.py | 9 ++++++--- backend/product/models.py | 5 ++++- 9 files changed, 44 insertions(+), 29 deletions(-) diff --git a/backend/account/models.py b/backend/account/models.py index 3863b82..baf3fdf 100644 --- a/backend/account/models.py +++ b/backend/account/models.py @@ -2,6 +2,9 @@ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, Permis from django.db import models from django.utils.translation import gettext_lazy as _ import random +import logging + +logger = logging.getLogger(__name__) from datetime import datetime, timedelta from django.utils import timezone from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken, OutstandingToken @@ -113,7 +116,7 @@ class User(AbstractBaseUser, PermissionsMixin): for token in tokens: BlacklistedToken.objects.get_or_create(token=token) except Exception as e: - print(f"block list error: {e}") + logger.error(f"block list error: {e}") def __str__(self): @@ -200,7 +203,6 @@ class PushSubscription(models.Model): "icon": 'https://api.heymlz.com' + icon, "image": 'https://api.heymlz.com' + icon, } - print(payload) try: webpush( subscription_info={ @@ -214,7 +216,7 @@ class PushSubscription(models.Model): } ) except WebPushException as ex: - print("Failed to send notification:", ex) + logger.error(f"Failed to send notification: {ex}") @classmethod def send_group_notification(cls, user, title, body): @@ -240,7 +242,7 @@ class PushSubscription(models.Model): } ) except WebPushException as ex: - print(f"Failed to send notification to {sub.user}:", ex) + logger.error(f"Failed to send notification to {sub.user}: {ex}") @@ -277,10 +279,10 @@ def get_location_from_ip(ip_address): if data["status"] == "success": return data['country'], data['regionName'], data['city'], data.get('zip', 'ناموجود'), data['lat'], data['lon'], data['isp'] else: - print("Error fetching data: ", data["message"]) + logger.error(f"Error fetching data: {data['message']}") return None except Exception as e: - print(f"An error occurred: {e}") + logger.error(f"An error occurred: {e}") return None class SecurityBreachAttemptModel(models.Model): diff --git a/backend/chat/models.py b/backend/chat/models.py index ebbf5e4..0820302 100644 --- a/backend/chat/models.py +++ b/backend/chat/models.py @@ -1,5 +1,8 @@ from django.db import models from account.models import User +import logging + +logger = logging.getLogger(__name__) from product.models import ProductModel from django.conf import settings import openai @@ -55,7 +58,7 @@ class ProductChatModel(models.Model): self.thread = thread.id except Exception as e: - print(f'error in chat class: {e}') + logger.error(f'error in chat class: {e}') raise ValueError(f"Error creating OpenAI thread: {e}") super().save(*args, **kwargs) \ No newline at end of file diff --git a/backend/core/views.py b/backend/core/views.py index 9894f4e..06c55ee 100644 --- a/backend/core/views.py +++ b/backend/core/views.py @@ -1,7 +1,10 @@ import json import random +import logging from functools import lru_cache +logger = logging.getLogger(__name__) + from django.contrib.humanize.templatetags.humanize import intcomma from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ @@ -274,9 +277,7 @@ class FakeAdminLoginView(View): ip = x_forwarded_for.split(',')[0] else: ip = request.META.get("REMOTE_ADDR") - print(ip) - print(len(ip)) - print(type(ip)) + logger.info(f"Honeypot GET request from IP: {ip}, length: {len(ip)}, type: {type(ip).__name__}") hacker, created = SecurityBreachAttemptModel.objects.get_or_create(ip_address=ip) return render(request, 'admin/fake_login.html', self.get_context(request)) @@ -286,7 +287,7 @@ class FakeAdminLoginView(View): ip = x_forwarded_for.split(',')[0] else: ip = request.META.get("REMOTE_ADDR") - print(ip) + logger.warning(f"Honeypot POST request from IP: {ip}") hacker, created = SecurityBreachAttemptModel.objects.get_or_create(ip_address=ip) hacker.trys += 1 hacker.save() diff --git a/backend/order/admin.py b/backend/order/admin.py index 2977048..d4891cc 100644 --- a/backend/order/admin.py +++ b/backend/order/admin.py @@ -1,5 +1,8 @@ from django.contrib import admin, messages from .models import * +import logging + +logger = logging.getLogger(__name__) from unfold.admin import TabularInline, StackedInline from unfold.contrib.inlines.admin import NonrelatedTabularInline from django.db.models import Q @@ -35,8 +38,7 @@ class OrderItemAdmin(ModelAdmin): if not hasattr(request.user, 'shop'): return False - print(obj.product.product.shop) - print(request.user.shop) + logger.debug(f"Shop permissions check: obj.shop={obj.product.product.shop}, user.shop={request.user.shop}") return request.user.shop == obj.product.product.shop diff --git a/backend/order/models.py b/backend/order/models.py index 6aaa63c..6a45879 100644 --- a/backend/order/models.py +++ b/backend/order/models.py @@ -1,5 +1,8 @@ from account.models import SpecialDiscountCode from django.db import models, transaction +import logging + +logger = logging.getLogger(__name__) from account.models import User, UserAddressModel, PushSubscription from product.models import ProductModel, ProductVariant, ProductImageModel from django.utils import timezone @@ -33,7 +36,7 @@ class DiscountCode(models.Model): elif not self.quantity > 0: return 'این کد تخفیف تمام شده است' else: - print('log later bug') + logger.warning('Discount code validity check failed') class Cart(models.Model): @@ -168,8 +171,8 @@ class OrderModel(models.Model): null=True, related_name='orders', verbose_name='کاربر') address = models.ForeignKey(UserAddressModel, on_delete=models.SET_NULL, related_name='orders', null=True, verbose_name='ادرس') - created_at = jmodels.jDateField( - blank=True, null=True, verbose_name="تاریخ ثبت سفارش") + created_at = models.DateTimeField( + auto_now_add=True, verbose_name="تاریخ ثبت سفارش") is_paid = models.BooleanField(default=False, verbose_name="وضعیت پرداخت") discount_code = models.ForeignKey( DiscountCode, on_delete=models.PROTECT, null=True, blank=True, verbose_name="کدتخفیف") @@ -227,9 +230,7 @@ class OrderModel(models.Model): return True except Exception as e: - print(e) - # Log the error if you have logging setup - # logger.error(f"Failed to rollback stock for order {self.pk}: {e}") + logger.error(f"Failed to rollback stock for order {self.pk}: {e}") return False @@ -264,7 +265,7 @@ class OrderItemModel(models.Model): # @property def price_after_special_discount(self): all_discounts = (self.special_discount_amount or 0) + self.total_product_discount_amount() - print(all_discounts) + logger.debug(f"Total discounts calculated: {all_discounts}") return self.total_price_before_discount() - all_discounts def unit_price(self): diff --git a/backend/order/tasks.py b/backend/order/tasks.py index a19edab..cd23bd3 100644 --- a/backend/order/tasks.py +++ b/backend/order/tasks.py @@ -40,8 +40,8 @@ def send_change_status_notif(instance_pk, new_status): for user_sub in user_subs: try: user_sub.send_notif(f'سفارش شما به {new_status} تغییر کرد', f'سفارش شما به {new_status} تغییر کرد', ProductImageModel.objects.all().first().image.url) - except: - print('log later send notif error') + except Exception as e: + logger.error('Error sending status notification: ' + str(e)) @shared_task def send_change_status_sms(instance_pk, new_status): @@ -77,7 +77,7 @@ def generate_daily_shop_reports(): from .models import ShopOrderModel, ShopDailyReport target_date = (timezone.now() - timedelta(days=1)).date() - print(f'Generating shop reports for {target_date}') + logging.info(f'Generating shop reports for {target_date}') shop_orders = ShopOrderModel.objects.filter(created_at__date=target_date) if not shop_orders.exists(): diff --git a/backend/order/views.py b/backend/order/views.py index f33681c..85a8255 100644 --- a/backend/order/views.py +++ b/backend/order/views.py @@ -390,13 +390,13 @@ class PaymentView(APIView): }) except AZBankGatewaysException as e: - print(f"Payment gateway error: {e}") + logger.error(f"Payment gateway error: {e}") return Response({ 'error': 'خطا در اتصال به درگاه پرداخت' }, status=status.HTTP_400_BAD_REQUEST) except Exception as e: - print(f"Order creation error: {e}") + logger.error(f"Order creation error: {e}") return Response({ 'error': 'خطا در ثبت سفارش' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/backend/product/admin.py b/backend/product/admin.py index 6e12065..d0db23f 100644 --- a/backend/product/admin.py +++ b/backend/product/admin.py @@ -1,5 +1,8 @@ from django.contrib import admin, messages from django import forms +import logging + +logger = logging.getLogger(__name__) # from product.tasks import update_prices from .models import * from unfold.admin import TabularInline, StackedInline @@ -263,13 +266,13 @@ class ProductDetailModel1Admin(ModelAdmin, ImportExportModelAdmin): def get_queryset(self, request): if request.user.is_superuser: - print('here') + logger.info('Returning all ProductDetailModels for superuser') return ProductDetailModel.objects.all() if not hasattr(request.user, 'shop'): - print(' in here 2') + logger.info('User has no shop, returning empty queryset') return ProductDetailModel.objects.none() - print('in here 3') + logger.info('Filtering ProductDetailModels by shop') queryset = ProductDetailModel.objects.filter(product__product__shop__id=request.user.shop.id) return queryset diff --git a/backend/product/models.py b/backend/product/models.py index 808f666..27f242a 100644 --- a/backend/product/models.py +++ b/backend/product/models.py @@ -1,5 +1,8 @@ from django.db import models from django.utils.text import slugify +import logging + +logger = logging.getLogger(__name__) from account.models import User from django.urls import reverse import requests @@ -148,7 +151,7 @@ class DollorModel(models.Model): data = response.json() price = int(data["lastTradePrice"]) price_in_usd = price / 10.0 - print('\n\nprice from api \n\n') + logger.info('Price fetched from API') except Exception as e: return self.defualt_price