Skip to content

Instantly share code, notes, and snippets.

View specialunderwear's full-sized avatar

Voxin Muyli specialunderwear

View GitHub Profile
class SomeView(View):
model_admin = None
def get_context_data(self, **kwargs):
return super().get_context_data(
**self.model_admin.admin_site.each_context(self.request)
)
class FakeAdmin:
def __init__(self, model, admin_site):
class KeyedItems(dict):
"""
KeyedItems allow you to create a dict from a list of dicts, keyed by the parameter passed
as key. If no param is passed the entire item will be the key. KeyedItems will
not process the entire list, but processing will only proceed up to the item
that you requested was found, saving memory and processing time.
This is demonstrated below by using an infinite list generated by count.
>>> from itertools import count
# Generated by Django 2.2 on 2019-04-22 12:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('through', '0001_initial'),
]
@specialunderwear
specialunderwear / metainnerclass.py
Last active July 12, 2019 09:08
Have a Meta inner class like in django, that will turn into a _meta attribute.
from django.utils.functional import cached_property
class MetaClass(object):
def __init__(self, attrs, endpointname):
self.__dict__.update(attrs)
self.endpointname = endpointname
@cached_property
def endpoint(self):
from contextlib import contextmanager
from unittest.mock import patch
@contextmanager
def fake_autocreated(many_to_many_manager):
"Do not give a shit about any intermediate models, just update the relation"
with patch.object(many_to_many_manager.through._meta, "auto_created", True):
yield many_to_many_manager
from copy import deepcopy
from unittest import mock
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.translation import override
from django.template import base as template
from django.template import defaulttags
from oscar.core.loading import get_model
from django.db import models
class ThroughFooBars(models.Model):
foo = models.ForeignKey('ThroughFoo', models.DO_NOTHING)
bar = models.ForeignKey('ThroughBar', models.DO_NOTHING)
order = models.PositiveIntegerField()
class Meta:
managed = False
# Generated by Django 2.2 on 2019-04-22 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('through', '0001_initial'),
]
from django.db import models
class Bar(models.Model):
spam = models.EmailField()
class Foo(models.Model):
bars = models.ManyToManyField(Bar, through='ThroughFooBars')
@specialunderwear
specialunderwear / initialize.py
Created May 11, 2017 13:06
Initialize a package directory structure with __init__.py files.
#! /usr/bin/env python
import os
import argparse
def visit(arg, dirname, names):
name = os.path.join(arg, dirname, '__init__.py')
if not os.path.exists(name):
open(name, 'a').close()