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'
You might also like...
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App 💛 We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

django-quill-editor makes Quill.js easy to use on Django Forms and admin sites
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot 🚀 Features A Django stater project with fully basic requirements for a production-ready

pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-django allows you to test your Django project/applications with the pytest testing tool.

APIs for a Chat app. Written with Django Rest framework and Django channels.
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

Comments
  • update project name in GitHub url setup arg

    update project name in GitHub url setup arg

    s/django_extra_tools/django-extra-tools/

    It's a tiny change but it fixes the link from PyPI to the repository. If you don't like small commits in your git history, feel free to ignore this PR and just fix it whenever you next update setup. 😄

    Thanks for sharing your code!

    opened by reduxionist 1
Owner
Tomasz Jakub Rup
Owner of @go-loremipsum @go-passwd @protobuf-gis @gosoap
Tomasz Jakub Rup
A simple demonstration of how a django-based website can be set up for local development with microk8s

Django with MicroK8s Start Building Your Project This project provides a Django web app running as a single node Kubernetes cluster in microk8s. It is

Noah Jacobson 19 Oct 22, 2022
A set of high-level abstractions for Django forms

django-formtools Django's "formtools" is a set of high-level abstractions for Django forms. Currently for form previews and multi-step forms. This cod

Jazzband 621 Dec 30, 2022
Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app.

django-permissions-policy Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app. Requirements Python 3.

Adam Johnson 78 Jan 2, 2023
I managed to attach the Django Framework to my Telegram Bot and set a webhook

I managed to attach the Django Framework to my Telegram Bot and set a webhook. I've been developing it from 10th of November 2021 and I want to have a basic working prototype.

Valentyn Vovchak 2 Sep 8, 2022
DCM is a set of tools that helps you to keep your data in your Django Models consistent.

Django Consistency Model DCM is a set of tools that helps you to keep your data in your Django Models consistent. Motivation You have a lot of legacy

Occipital 59 Dec 21, 2022
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Marco Bonetti 909 Dec 26, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022