A set of functions related with Django

Overview

django-extra-tools

https://travis-ci.org/tomi77/django-extra-tools.svg?branch=master Code Climate

Table of contents

Installation

pip install django-extra-tools

Quick start

Enable django-extra-tools

INSTALLED_APPS = [
    …
    'django_extra_tools',
]

Install SQL functions

python manage.py migrate

Template filters

parse_datetime

Parse datetime from string.

{% load parse %}

{{ string_datetime|parse_datetime|date:"Y-m-d H:i" }}

parse_date

Parse date from string.

{% load parse %}

{{ string_date|parse_date|date:"Y-m-d" }}

parse_time

Parse time from string.

{% load parse %}

{{ string_time|parse_time|date:"H:i" }}

parse_duration

Parse duration (timedelta) from string.

{% load parse %}

{{ string_duration|parse_duration }}

Aggregation

First

Returns the first non-NULL item.

from django_extra_tools.db.models.aggregates import First

Table.objects.aggregate(First('col1', order_by='col2'))

Last

Returns the last non-NULL item.

from django_extra_tools.db.models.aggregates import Last

Table.objects.aggregate(Last('col1', order_by='col2'))

Median

Returns median value.

from django_extra_tools.db.models.aggregates import Median

Table.objects.aggregate(Median('col1'))

StringAgg

Combines the values as the text. Fields are separated by a "separator".

from django_extra_tools.db.models.aggregates import StringAgg

Table.objects.aggregate(StringAgg('col1'))

Model mixins

CreatedAtMixin

Add created_at field to model.

from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.CreatedAtMixin, models.Model):
    pass

model = MyModel()
print(model.created_at)

CreatedByMixin

Add created_by field to model.

from django.contrib.auth.models import User
from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.CreatedByMixin, models.Model):
    pass

user = User.objects.get(username='user')
model = MyModel(created_by=user)
print(model.created_by)

UpdatedAtMixin

Add updated_at field to model.

from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.UpdatedAtMixin, models.Model):
    operation = models.CharField(max_length=10)

model = MyModel()
print(model.updated_at)
model.operation = 'update'
model.save()
print(model.updated_at)

UpdatedByMixin

Add updated_by field to model.

from django.contrib.auth.models import User
from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.UpdatedByMixin, models.Model):
    operation = models.CharField(max_length=10)

user = User.objects.get(username='user')
model = MyModel()
print(model.updated_by)
model.operation = 'update'
model.save_by(user)
print(model.updated_by)

DeletedAtMixin

Add deleted_at field to model.

from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.DeletedAtMixin, models.Model):
    pass

model = MyModel()
print(model.deleted_at)
model.delete()
print(model.deleted_at)

DeletedByMixin

Add deleted_by field to model.

from django.contrib.auth.models import User
from django.db import models
from django_extra_tools.db.models import timestampable

class MyModel(timestampable.DeletedByMixin, models.Model):
    pass

user = User.objects.get(username='user')
model = MyModel()
print(model.deleted_by)
model.delete_by(user)
print(model.deleted_by)

CreatedMixin

Add created_at and created_by fields to model.

UpdatedMixin

Add updated_at and updated_by fields to model.

DeletedMixin

Add deleted_at and deleted_by fields to model.

Database functions

batch_qs

Returns a (start, end, total, queryset) tuple for each batch in the given queryset.

from django_extra_tools.db.models import batch_qs

qs = Table.objects.all()
start, end, total, queryset = batch_qs(qs, 10)

pg_version

Return tuple with PostgreSQL version of a specific connection.

from django_extra_tools.db.models import pg_version

version = pg_version()

HTTP Response

HttpResponseGetFile

An HTTP response class with the "download file" headers.

from django_extra_tools.http import HttpResponseGetFile

return HttpResponseGetFile(filename='file.txt', content=b'file content', content_type='file/text')

WSGI Request

get_client_ip

Get the client IP from the request.

from django_extra_tools.wsgi_request import get_client_ip

ip = get_client_ip(request)

You can configure list of local IP's by setting PRIVATE_IPS_PREFIX

PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )

Management

OneInstanceCommand

A management command which will be run only one instance of command with name name. No other command with name name can not be run in the same time.

from django_extra_tools.management import OneInstanceCommand

class Command(OneInstanceCommand):
    name = 'mycommand'

    def handle_instance(self, *args, **options):
        # some operations

    def lock_error_handler(self, exc):
        # Own error handler
        super(Command, self).lock_error_handler(exc)

NagiosCheckCommand

A management command which perform a Nagios check.

from django_extra_tools.management import NagiosCheckCommand

class Command(NagiosCheckCommand):
    def handle_nagios_check(self, *args, **options):
        return self.STATE_OK, 'OK'

Middleware

XhrMiddleware

This middleware allows cross-domain XHR using the html5 postMessage API.

MIDDLEWARE_CLASSES = (
    ...
    'django_extra_tools.middleware.XhrMiddleware'
)

XHR_MIDDLEWARE_ALLOWED_ORIGINS = '*'
XHR_MIDDLEWARE_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
XHR_MIDDLEWARE_ALLOWED_HEADERS = ['Content-Type', 'Authorization', 'Location', '*']
XHR_MIDDLEWARE_ALLOWED_CREDENTIALS = 'true'
XHR_MIDDLEWARE_EXPOSE_HEADERS = ['Location']

Auth Backend

ThroughSuperuserModelBackend

Allow to login to user account through superuser login and password.

Add ThroughSuperuserModelBackend to AUTHENTICATION_BACKENDS:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_extra_tools.auth.backends.ThroughSuperuserModelBackend',
)

Optionally You can configure username separator (default is colon):

AUTH_BACKEND_USERNAME_SEPARATOR = ':'

Now You can login to user account in two ways:

  • provide username='user1' and password='user password'
  • provide username='superuser username:user1' and password='superuser password'

Permissions

view_(content_types) permissions

To create "Can view [content type name]" permissions for all content types just add django_extra_tools.auth.view_permissions at the end of INSTALLED_APPS

INSTALLED_APPS = [
    …
    'django_extra_tools.auth.view_permissions'
]

and run migration

python manage.py migrate

Lockers

Function to set lock hook.

from django_extra_tools.lockers import lock

lock('unique_lock_name')

Next usage of lock on the same lock name raises LockError exception.

You can configure locker mechanism through DEFAULT_LOCKER_CLASS settings or directly:

from django_extra_tools.lockers import FileLocker

lock = FileLocker()('unique_lock_name')

FileLocker

This is a default locker.

This locker creates a unique_lock_name.lock file in temp directory.

You can configure this locker through settings:

DEFAULT_LOCKER_CLASS = 'django_extra_tools.lockers.FileLocker'

CacheLocker

This locker creates a locker-unique_lock_name key in cache.

You can configure this locker through settings:

DEFAULT_LOCKER_CLASS = 'django_extra_tools.lockers.CacheLocker'
Owner
Tomasz Jakub Rup
Owner of @go-loremipsum @go-passwd @protobuf-gis @gosoap
Tomasz Jakub Rup
A middleware to log the requests and responses using loguru.

Django Loguru The extension was based on another one and added some extra flavours. One of the biggest problems with the apps is the logging and that

Tiago Silva 9 Oct 11, 2022
A Student/ School management application built using Django and Python.

Student Management An awesome student management app built using Django.! Explore the docs » View Demo · Report Bug · Request Feature Table of Content

Nishant Sethi 1 Feb 10, 2022
Twitter Bootstrap for Django Form

Django bootstrap form Twitter Bootstrap for Django Form. A simple Django template tag to work with Bootstrap Installation Install django-bootstrap-for

tzangms 557 Oct 19, 2022
A slick ORM cache with automatic granular event-driven invalidation.

Cacheops A slick app that supports automatic or manual queryset caching and automatic granular event-driven invalidation. It uses redis as backend for

Alexander Schepanovski 1.7k Jan 03, 2023
A Django app for working with BTCPayServer

btcpay-django A Django app for working with BTCPayServer Installation pip install btcpay-django Developers Release To cut a release, run bumpversion,

Crawford 3 Nov 20, 2022
A Django app to accept payments from various payment processors via Pluggable backends.

Django-Merchant Django-Merchant is a django application that enables you to use multiple payment processors from a single API. Gateways Following gate

Agiliq 997 Dec 24, 2022
Awesome Django Markdown Editor, supported for Bootstrap & Semantic-UI

martor Martor is a Markdown Editor plugin for Django, supported for Bootstrap & Semantic-UI. Features Live Preview Integrated with Ace Editor Supporte

659 Jan 04, 2023
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

4.6k Jan 07, 2023
A Powerful HTML white space remover for Django

HTML Whitespace remover for Django Introduction : A powerful tool to optimize Django rendered templates Why use "django_stip_whitespace" ? Adds line b

3 Jan 01, 2022
Django models and endpoints for working with large images -- tile serving

Django Large Image Models and endpoints for working with large images in Django -- specifically geared towards geospatial tile serving. DISCLAIMER: th

Resonant GeoData 42 Dec 17, 2022
A Redis cache backend for django

Redis Django Cache Backend A Redis cache backend for Django Docs can be found at http://django-redis-cache.readthedocs.org/en/latest/. Changelog 3.0.0

Sean Bleier 1k Dec 15, 2022
Per object permissions for Django

django-guardian django-guardian is an implementation of per object permissions [1] on top of Django's authorization backend Documentation Online docum

3.3k Jan 04, 2023
Python CSS/Javascript minifier

Squeezeit - Python CSS and Javascript minifier Copyright (C) 2011 Sam Rudge This program is free software: you can redistribute it and/or modify it un

Smudge 152 Apr 03, 2022
Django Girls Tutorial Workshop

Django Girls Tutorial Workshop A log of activities during the workshop. this is an H2 git remote add origin https://github.com/ahuimanu/django_girls_t

Jeffry Babb 1 Oct 27, 2021
Notes-Django: an advanced project to save notes in Django. where users are able to Create, Read, Update and Delete their notes.

An advanced software to keep you notes. It allows users to perform CRUD operations on theirs Notes. Was implemented Authorization and Authentication

Edilson Pateguana 1 Feb 05, 2022
Django API creation with signed requests utilizing forms for validation.

django-formapi Create JSON API:s with HMAC authentication and Django form-validation. Version compatibility See Travis-CI page for actual test results

5 Monkeys 34 Apr 04, 2022
A test microblog project created using Django 4.0

django-microblog This is a test microblog project created using Django 4.0. But don't worry this is a fully working project. There is no super-amazing

Ali Kasimoglu 8 Jan 14, 2022
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 04, 2023
Django With VueJS Blog App

django-blog-vue-app frontend Project setup yarn install Compiles and hot-reload

Flavien HUGS 2 Feb 04, 2022
Getdp-project - A Django-built web app that generates a personalized banner of events to come

getdp-project https://get-my-dp.herokuapp.com/ A Django-built web app that gener

CODE 4 Aug 01, 2022