Skip to content

Instantly share code, notes, and snippets.

@Dimitrionian
Dimitrionian / filtration.py
Created April 11, 2023 06:59
Generalized queryset filtration by different fields
@classmethod
def filter_by_field(cls, filter_str: str, field: str, items: QuerySet) -> QuerySet:
"""Filter page items by different fields"""
criterion = {
f'{field}__contains': filter_str
}
return items.filter(**criterion)
@Dimitrionian
Dimitrionian / tablib.py
Created May 15, 2020 21:28
Base tablib excel format modification to allow creating multiple excel tabs, in this case two tabs. Tablib library doesn't allow this out of the box
class ModifiedTablibFormat(TablibFormat):
def export_data(self, dataset, **kwargs):
return self.export_set(dataset, **kwargs)
def export_set(self, dataset, freeze_panes=True):
"""
Returns XLSX representation of Dataset.
"""
wb = Workbook()
@Dimitrionian
Dimitrionian / channels.py
Last active May 15, 2020 21:36
Async Django Channels 2.0 chat inspired by the work of Andrew Godwin (author of Channels framework)
from django.conf import settings
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from .exceptions.client import ClientError
from .utils import get_chat_or_error, create_message, get_page
class ChatConsumer(AsyncJsonWebsocketConsumer):
"""
This chat consumer handles websocket connections for chat clients.
@Dimitrionian
Dimitrionian / check_permissions.py
Last active October 20, 2021 11:53
Permission class for checking previously assigned permissions
class IsPermittedAccess(BasePermission):
@staticmethod
def get_code_name(view, request, permission_map):
model_name = view.queryset.model._meta.model_name
app_label = view.queryset.model._meta.app_label
return '{}.{}_{}'.format(app_label,
permission_map.get(request.method),
model_name)
@Dimitrionian
Dimitrionian / IoT.py
Last active February 16, 2018 20:45
Filter Alerts by roles
from django.db import models
from django.db.models import Q
from wirelesstag.models import TagManager
from guardian.shortcuts import get_objects_for_user
class AlertQuerySet(models.QuerySet):
def for_user(self, user):
if user.groups.filter(name='Company administrators').exists():
alerts = self.filter(