• Stars
    star
    1,471
  • Rank 31,964 (Top 0.7 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 12 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use Database URLs in your Django Application.

DJ-Database-URL

Jazzband https://codecov.io/gh/jazzband/dj-database-url/branch/master/graph/badge.svg?token=7srBUpszOa

This simple Django utility allows you to utilize the 12factor inspired DATABASE_URL environment variable to configure your Django application.

The dj_database_url.config method returns a Django database connection dictionary, populated with all the data specified in your URL. There is also a conn_max_age argument to easily enable Django's connection pool.

If you'd rather not use an environment variable, you can pass a URL in directly instead to dj_database_url.parse.

Supported Databases

Support currently exists for PostgreSQL, PostGIS, MySQL, MySQL (GIS), Oracle, Oracle (GIS), Redshift, CockroachDB, Timescale, Timescale (GIS) and SQLite.

Installation

Installation is simple:

$ pip install dj-database-url

Usage

  1. If DATABASES is already defined:
  • Configure your database in settings.py from DATABASE_URL:

    import dj_database_url
    
    DATABASES['default'] = dj_database_url.config(
        conn_max_age=600,
        conn_health_checks=True,
    )
  • Provide a default:

    DATABASES['default'] = dj_database_url.config(
        default='postgres://...',
        conn_max_age=600,
        conn_health_checks=True,
    )
  • Parse an arbitrary Database URL:

    DATABASES['default'] = dj_database_url.parse(
        'postgres://...',
        conn_max_age=600,
        conn_health_checks=True,
    )
  1. If DATABASES is not defined:
  • Configure your database in settings.py from DATABASE_URL:

    import dj_database_url
    
    DATABASES = {
        'default': dj_database_url.config(
            conn_max_age=600,
            conn_health_checks=True,
        ),
    }
  • You can provide a default, used if the DATABASE_URL setting is not defined:

    DATABASES = {
        'default': dj_database_url.config(
            default='postgres://...',
            conn_max_age=600,
            conn_health_checks=True,
        )
    }
  • Parse an arbitrary Database URL:

    DATABASES = {
        'default': dj_database_url.parse(
            'postgres://...',
            conn_max_age=600,
            conn_health_checks=True,
        )
    }

conn_max_age sets the CONN_MAX_AGE setting, which tells Django to persist database connections between requests, up to the given lifetime in seconds. If you do not provide a value, it will follow Django’s default of 0. Setting it is recommended for performance.

conn_health_checks sets the CONN_HEALTH_CHECKS setting (new in Django 4.1), which tells Django to check a persisted connection still works at the start of each request. If you do not provide a value, it will follow Django’s default of False. Enabling it is recommended if you set a non-zero conn_max_age.

Strings passed to dj_database_url must be valid URLs; in particular, special characters must be url-encoded. The following url will raise a ValueError:

postgres://user:p#ssword!@localhost/foobar

and should instead be passed as:

postgres://user:p%23ssword!@localhost/foobar

TEST settings can be configured using the test_options attribute:

DATABASES['default'] = dj_database_url.config(default='postgres://...', test_options={'NAME': 'mytestdatabase'})

URL schema

Engine Django Backend URL
PostgreSQL django.db.backends.postgresql [1] postgres://USER:PASSWORD@HOST:PORT/NAME [2]
PostGIS django.contrib.gis.db.backends.postgis postgis://USER:PASSWORD@HOST:PORT/NAME
MSSQL sql_server.pyodbc mssql://USER:PASSWORD@HOST:PORT/NAME
MSSQL [5] mssql mssqlms://USER:PASSWORD@HOST:PORT/NAME
MySQL django.db.backends.mysql mysql://USER:PASSWORD@HOST:PORT/NAME [2]
MySQL (GIS) django.contrib.gis.db.backends.mysql mysqlgis://USER:PASSWORD@HOST:PORT/NAME
SQLite django.db.backends.sqlite3 sqlite:///PATH [3]
SpatiaLite django.contrib.gis.db.backends.spatialite spatialite:///PATH [3]
Oracle django.db.backends.oracle oracle://USER:PASSWORD@HOST:PORT/NAME [4]
Oracle (GIS) django.contrib.gis.db.backends.oracle oraclegis://USER:PASSWORD@HOST:PORT/NAME
Redshift django_redshift_backend redshift://USER:PASSWORD@HOST:PORT/NAME
CockroachDB django_cockroachdb cockroach://USER:PASSWORD@HOST:PORT/NAME
Timescale [6] timescale.db.backends.postgresql timescale://USER:PASSWORD@HOST:PORT/NAME
Timescale (GIS) [6] timescale.db.backend.postgis timescalegis://USER:PASSWORD@HOST:PORT/NAME
[1]The django.db.backends.postgresql backend is named django.db.backends.postgresql_psycopg2 in older releases. For backwards compatibility, the old name still works in newer versions. (The new name does not work in older versions).
[2](1, 2) With PostgreSQL or CloudSQL, you can also use unix domain socket paths with percent encoding: postgres://%2Fvar%2Flib%2Fpostgresql/dbname mysql://uf07k1i6d8ia0v@%2fcloudsql%2fproject%3alocation%3ainstance/dbname
[3](1, 2) SQLite connects to file based databases. The same URL format is used, omitting the hostname, and using the "file" portion as the filename of the database. This has the effect of four slashes being present for an absolute file path: sqlite:////full/path/to/your/database/file.sqlite.
[4]Note that when connecting to Oracle the URL isn't in the form you may know from using other Oracle tools (like SQLPlus) i.e. user and password are separated by : not by /. Also you can omit HOST and PORT and provide a full DSN string or TNS name in NAME part.
[5]Microsoft official mssql-django adapter.
[6](1, 2) Using the django-timescaledb Package which must be installed.

Contributing

We welcome contributions to this project. Projects can take two forms:

  1. Raising issues or helping others through the github issue tracker.
  2. Contributing code.

Raising Issues or helping others:

When submitting an issue or helping other remember you are talking to humans who have feelings, jobs and lives of their own. Be nice, be kind, be polite. Remember english may not be someone first language, if you do not understand or something is not clear be polite and re-ask/ re-word.

Contributing code:

  • Before writing code be sure to check existing PR's and issues in the tracker.
  • Write code to the pylint spec.
  • Large or wide sweeping changes will take longer, and may face more scrutiny than smaller confined changes.
  • Code should be pass black and flake8 validation.

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
8,023
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,668
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,586
star
4

django-silk

Silky smooth profiling for Django
Python
4,380
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,957
star
6

django-taggit

Simple tagging for django
Python
3,307
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,148
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,860
star
9

django-model-utils

Django model mixins and utilities.
Python
2,638
star
10

Watson

⌚ A wonderful CLI to track your time!
Python
2,450
star
11

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,275
star
12

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,189
star
13

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,077
star
14

sorl-thumbnail

Thumbnails for Django
Python
1,743
star
15

django-constance

Dynamic Django settings.
Python
1,687
star
16

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,679
star
17

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,648
star
18

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,508
star
19

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,463
star
20

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,336
star
21

django-tinymce

TinyMCE integration for Django
JavaScript
1,270
star
22

django-analytical

Analytics services for Django projects
Python
1,197
star
23

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,185
star
24

django-rest-knox

Authentication Module for django rest auth
Python
1,130
star
25

django-waffle

A feature flipper for Django
Python
1,128
star
26

django-smart-selects

chained and grouped selects for django forms
Python
1,125
star
27

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
1,108
star
28

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,085
star
29

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
1,035
star
30

django-payments

Universal payment handling for Django.
Python
1,023
star
31

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
977
star
32

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
959
star
33

geojson

Python bindings and utilities for GeoJSON
Python
913
star
34

django-nose

Django test runner using nose
Python
882
star
35

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
845
star
36

django-floppyforms

Full control of form rendering in the templates.
Python
841
star
37

django-avatar

A Django app for handling user avatars.
Python
806
star
38

django-formtools

A set of high-level abstractions for Django forms
Python
790
star
39

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
616
star
40

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
564
star
41

django-invitations

Generic invitations app for Django
Python
557
star
42

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
511
star
43

django-recurrence

Utility for working with recurring dates in Django.
Python
475
star
44

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
458
star
45

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
457
star
46

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
394
star
47

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
48

django-downloadview

Serve files with Django.
Python
378
star
49

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
343
star
50

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
335
star
51

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
316
star
52

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
53

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
300
star
54

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
292
star
55

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
264
star
56

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
252
star
57

django-fsm-log

Automatic logging for Django FSM
Python
242
star
58

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
59

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
224
star
60

django-celery-monitor

Celery Monitoring for Django
Python
197
star
61

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
178
star
62

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
63

icalevents

Python module for iCal URL/file parsing and querying.
Python
156
star
64

django-voting

A generic voting application for Django
Python
99
star
65

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
92
star
66

django-redshift-backend

Redshift database backend for Django
Python
83
star
67

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
68

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
81
star
69

website

Code for the Jazzband website
Python
66
star
70

django-sorter

A helper app for sorting objects in Django templates.
Python
54
star
71

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
72

django-fernet-encrypted-fields

Python
47
star
73

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
38
star
74

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
33
star
75

help

Use this repo to get help from the roadies
27
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
9
star
77

.github

Community health and config files for Jazzband
7
star
78

admin

Some admin files for Jazzband
3
star
79

actions

Various GitHub actions for Jazzband projects
1
star