Skip to content

Instantly share code, notes, and snippets.

@hakib
hakib / custom_django_checks.py
Last active July 1, 2024 09:20
Custom django checks using Django check framework, inspect and ast.
"""
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.
@stevelacey
stevelacey / routers.py
Last active October 20, 2023 07:35
Django REST Framework custom API root view with permissions filter
from collections import OrderedDict
from myproject.api.views import APIRootView
from rest_framework import permissions, routers
from rest_framework_nested.routers import NestedSimpleRouter
class Router(routers.DefaultRouter):
include_root_view = True
include_format_suffixes = False
root_view_name = 'index'
@twidi
twidi / drf_utils.py
Created December 21, 2016 14:34
Make Django Rest Framework correctly handle Django ValidationError raised in the save method of a model
"""
Sometimes in your Django model you want to raise a ``ValidationError`` in the ``save`` method, for
some reason.
This exception is not managed by Django Rest Framework because it occurs after its validation
process. So at the end, you'll have a 500.
Correcting this is as simple as overriding the exception handler, by converting the Django
``ValidationError`` to a DRF one.
"""
from django.core.exceptions import ValidationError as DjangoValidationError
@danni
danni / migration_loaddata.py
Last active November 16, 2023 08:28 — forked from leifdenby/migration_loaddata.py
Django function for loading fixtures which use the current migration state of the model
import os
import logging
from django.core import serializers
LOGGER = logging.getLogger(__name__)
def load_fixture(app, fixture, ignorenonexistent=True):
"""
@leifdenby
leifdenby / migration_loaddata.py
Last active December 9, 2020 19:28
Django function for loading fixtures which use the current migration state of the model
from django.core import serializers
import os
def loaddata(fixture_name, apps, ignorenonexistent=True):
"""
Loads migrations that work at current state of a model, in constrast to
`loaddata` which requires a fixture to have data matching the fields
defined in `models.py`.
@Kmaschta
Kmaschta / DRF-dynamic-fields.py
Last active September 5, 2020 10:31
Django Rest Framework - Dynamic Fields
# How to display only interesting fields for a Django Rest Framework API
# /?fields=field1,field2,field3
from rest_framework import serializers, pagination
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
@goloveychuk
goloveychuk / modeldiffmixin.py
Last active September 10, 2021 06:18
modeldiffmixin.py
from django.forms.models import model_to_dict
class ModelDiffMixin(object):
def __init__(self, *args, **kwargs):
super(ModelDiffMixin, self).__init__(*args, **kwargs)
self.__initial = self._dict
@property
def diff(self):
@carymrobbins
carymrobbins / custom_manager.py
Last active December 16, 2022 14:11
Simple custom Model Manager for Django. Allows you to easy override QuerySet and EmptyQuerySet
from django.db import models
from django.db.models.query import EmptyQuerySet, QuerySet
class CustomManager(models.Manager):
"""
Easily override QuerySet by setting the QuerySet and EmptyQuerySet
inside of the class using inheritance.
"""
EmptyQuerySet = EmptyQuerySet
@mbylstra
mbylstra / scratchpad.py
Last active March 5, 2019 23:14
Django scratchpad file. A standalone Django script with the django environment loaded.Place in the root of your Django project. Assumes your settings.py is in a folder named 'main'.
import os
import sys
project_dir = os.path.realpath(__file__)
sys.path.append(project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'main.settings'
import django
from django.conf import settings
django.setup()