Skip to content

Instantly share code, notes, and snippets.

@hakib
hakib / django_markdown.py
Created March 30, 2020 15:10
Using Markdown in Django
View django_markdown.py
# Source code for article:
# https://hakibenita.com/django-markdown
from typing import Optional
import re
import markdown
from markdown.inlinepatterns import LinkInlineProcessor, LINK_RE
from urllib.parse import urlparse
from django.core.exceptions import ValidationError
@hakib
hakib / models.py
Created February 12, 2020 14:52
building-interactive-voice-response-ivr-system-python-django-twilio
View models.py
from django.db import models
class Theater(models.Model):
class Meta:
verbose_name = 'Theater'
verbose_name_plural = 'Theaters'
name = models.CharField(max_length=50)
View pytest_fixtures_as_parameters.py
import pytest
@pytest.fixture
def A():
return 1
@pytest.fixture
def B():
return 1
View beers.py
# https://hakibenita.com/fast-load-data-python-postgresql
from typing import Iterator, Dict, Any, Optional
from urllib.parse import urlencode
import datetime
#------------------------ Profile
import time
@hakib
hakib / admin.py
Last active May 3, 2023 12:32
How to Turn Django Admin Into a Lightweight Dashboard
View admin.py
# https://hakibenita.com/how-to-turn-django-admin-into-a-lightweight-dashboard
from django.contrib import admin
from django.db.models import Count, Sum, Min, Max, DateTimeField
from django.db.models.functions import Trunc
from . import models
def get_next_in_date_hierarchy(request, date_hierarchy):
@hakib
hakib / time_limited_paginator.py
Last active March 21, 2023 15:28
CountTimeoutLimitPaginator - Paginator that enforced a timeout on the count operation.
View time_limited_paginator.py
class TimeLimitedPaginator(Paginator):
"""
Paginator that enforced a timeout on the count operation.
When the timeout is reached a "fake" large value is returned instead,
Why does this hack exist? On every admin list view, Django issues a
COUNT on the full queryset. There is no simple workaround. On big tables,
this COUNT is extremely slow and makes things unbearable. This solution
is what we came up with.
"""
@hakib
hakib / custom_django_checks.py
Last active January 26, 2023 19:41
Custom django checks using Django check framework, inspect and ast.
View custom_django_checks.py
"""
Custom django checks.
H001: Field has no verbose name.
H002: Verbose name should use gettext.
H003: Words in verbose name must be all upper case or all lower case.
H004: Help text should use gettext.
H005: Model must define class Meta.
H006: Model has no verbose name.
H007: Model has no verbose name plural.
@hakib
hakib / admin.py
Created December 9, 2017 08:37
Django Admin InputFilter
View admin.py
# common/admin.py
class InputFilter(admin.SimpleListFilter):
template = 'admin/input_filter.html'
def lookups(self, request, model_admin):
# Dummy, required to show the filter.
return ((),)
def choices(self, changelist):