Skip to content

Instantly share code, notes, and snippets.

@mihalt
Created October 25, 2024 16:02
Show Gist options
  • Save mihalt/c2b131fb74b5126e94ef1de82b640ddf to your computer and use it in GitHub Desktop.
Save mihalt/c2b131fb74b5126e94ef1de82b640ddf to your computer and use it in GitHub Desktop.
import json
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db.models import Q, ForeignKey, ManyToManyField
from django.utils.html import mark_safe
from nested_admin.nested import NestedTabularInline
from communications.forms import MessageAdminForm
from communications.helpers import insert_smiles
from communications.models import PersonalSubscription, SubscriptionType, Offer, Message, message_messangers_models, \
SkypeMessage
from goods.admin import ProvidersStockInline
from keysbilling.admin import NotDisplayForAnyone
from keysbilling.helpers import display_new_line_in_admin
from orders.models import ClientOrder
from partners.models import Partner
class AccessedSender(admin.SimpleListFilter):
# Only draft yet
title = 'sender id in messanger'
parameter_name = 'sender'
def lookups(self, request, model_admin):
accessed_partners = list(Partner.objects.for_manager(request.user))
return ((partner.pk, partner.displayed_hidden_name) for partner in accessed_partners if
Message.objects.for_partner(partner).exists())
def queryset(self, request, queryset):
if partner_pk := self.value():
return queryset.for_partner(Partner.objects.get(pk=partner_pk))
class MessageAdmin(ModelAdmin):
readonly_fields = ['cleaned_text_custom', 'newsletter', 'separate_emotions']
list_editable = ['deserialize_cleaned_text_to_model']
list_display = readonly_fields + ['time_of_sending', 'updated', 'sender', 'recipients_names', 'deleted', 'resent',
'reason_of_not_approving_to_resend', 'white_text_applied'] + list_editable
list_filter = [AccessedSender]
list_display_links = ['cleaned_text_custom', 'time_of_sending', 'updated']
search_fields = ['cleaned_text', 'sender', 'recipients']
form = MessageAdminForm
list_per_page = 30
def recipients_names(self, obj):
return obj.get_recipients_names()
def cleaned_text_custom(self, obj):
txt = obj.cleaned_text
if obj.message_in_messanger_type == SkypeMessage.contenttype():
txt = insert_smiles(txt)
return display_new_line_in_admin(txt)
def separate_emotions(self, obj):
emotions = (emotion.render() for emotion in obj.get_emotions())
return mark_safe(' '.join(emotion for emotion in emotions if emotion))
def white_text_applied(self, obj):
return ', '.join(obj.applied_white_text.values_list('text', flat=True))
white_text_applied.admin_order_field = 'applied_white_text'
def previous_edited_message(self, obj):
return obj.message_in_messanger.previous_edited_message
def full_raw_data(self, obj):
return f'{json.dumps(obj.message_in_messanger.full_raw_data, indent=4, ensure_ascii=False)}'
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "message_in_messanger_type":
kwargs['limit_choices_to'] = Q()
for model in message_messangers_models:
kwargs['limit_choices_to'] |= Q(app_label=model._meta.app_label.lower(),
model=model._meta.model_name.lower())
if db_field.name == "deserialize_cleaned_text_to_model":
kwargs['limit_choices_to'] = Q()
for model in (ClientOrder, Offer):
kwargs['limit_choices_to'] |= Q(app_label=model._meta.app_label.lower(),
model=model._meta.model_name.lower())
return super().formfield_for_foreignkey(db_field, request, **kwargs)
def get_readonly_fields(self, request, obj=None):
if request.POST:
return []
additional = ['previous_edited_message']
if request.user.is_superuser:
additional += ['full_raw_data']
return additional + super().get_readonly_fields(request, obj)
def get_list_display(self, request):
additional = []
if request.user.is_superuser:
additional = ['file', 'picture']
return super().get_list_display(request) + additional
def get_autocomplete_fields(self, request):
autocomplete_fields = super().get_autocomplete_fields(request) or []
model_fields = self.model._meta.get_fields()
for f in model_fields:
if isinstance(f, ForeignKey) or isinstance(f, ManyToManyField) and not isinstance(f, GenericForeignKey):
autocomplete_fields.append(f.name)
return [f for f in autocomplete_fields if
f not in ['message_in_messanger_type', 'deserialize_cleaned_text_to_model']]
def get_exclude(self, request, obj=None):
exclude = super().get_exclude(request, obj) or []
if obj:
exclude += ['cleaned_text']
return exclude
def picture(self, obj):
return mark_safe(obj.render_image())
picture.admin_order_field = 'image'
class OfferAdmin(ModelAdmin):
fields = ['provider', 'price_expiration', 'automatically_generated', 'offer_full_text']
readonly_fields = ['added_at']
inlines = [ProvidersStockInline]
class SubscriptionInline(NestedTabularInline):
verbose_name_plural = 'Подписки'
exclude = ['end_time_of_subscription']
model = PersonalSubscription
extra = 1
admin.site.register(SubscriptionType, NotDisplayForAnyone)
admin.site.register(Offer, OfferAdmin)
admin.site.register(Message, MessageAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment