Django Helpers¶
This module file contains Django-specific helper functions, to help save time when developing with the Django framework.
handle_error - Redirects normal web page requests with a session error, outputs JSON with a status code for API queries.
is_database_synchronized - Check if all migrations have been ran before running code.
model_to_dict - Extract an individual Django model instance into a dict (with display names)
to_json - Convert a model Queryset into a plain string JSON array with display names
Copyright:
+===================================================+
| © 2019 Privex Inc. |
| https://www.privex.io |
+===================================================+
| |
| Originally Developed by Privex Inc. |
| License: X11 / MIT |
| |
| Core Developer(s): |
| |
| (+) Chris (@someguy123) [Privex] |
| (+) Kale (@kryogenic) [Privex] |
| |
+===================================================+
Copyright 2019 Privex Inc. ( https://www.privex.io )
Functions
|
Output an error as either a Django session message + redirect, or a JSON response based on whether the request was for the API readable version (?format=json) or not. |
|
Check if all migrations have been ran. |
|
1 dimensional json-ifyer for any Model |
|
Iterate a Django query set and dump to json str |
-
privex.helpers.django.
handle_error
(request: django.http.request.HttpRequest, err: str, rdr: django.http.response.HttpResponseRedirectBase, status=400)[source]¶ Output an error as either a Django session message + redirect, or a JSON response based on whether the request was for the API readable version (?format=json) or not.
Usage:
>>> from django.shortcuts import redirect >>> def my_view(request): ... return handle_error(request, "Invalid password", redirect('/login'), 403)
- Parameters
request (HttpRequest) – The Django request object from your view
err (str) – An error message as a string to display to the user / api call
rdr (HttpResponseRedirectBase) – A redirect() for normal browsers to follow after adding the session error.
status (int) – The HTTP status code to return if the request is an API call (default: 400 bad request)
-
privex.helpers.django.
is_database_synchronized
(database: str) → bool[source]¶ Check if all migrations have been ran. Useful for preventing auto-running code accessing models before the tables even exist, thus preventing you from migrating…
>>> from django.db import DEFAULT_DB_ALIAS >>> if not is_database_synchronized(DEFAULT_DB_ALIAS): >>> log.warning('Cannot run reload_handlers because there are unapplied migrations!') >>> return
- Parameters
database (str) – Which Django database config is being used? Generally just pass django.db.DEFAULT_DB_ALIAS
- Return bool
True if all migrations have been ran, False if not.