Skip to content

General Utilities

utils

CustomEncoder

Bases: DjangoJSONEncoder

Extended JSON encoder that handles Django FieldFile and lazy translation strings.

Falls back to force_text for any object the parent encoder cannot handle.

TempFiles(*files)

Bases: object

Context manager for a group of temporary files that are closed on exit.

TempFilesFromBytes(*file_bytes)

Bases: TempFiles

Context manager that writes byte sequences to temp files for the duration of the block.

TempFile(file)

Bases: object

Context manager for a single temporary file that is closed on exit.

global_request()

Return the current Django HTTP request from thread-local middleware.

Returns:

Name Type Description
HttpRequest

The current request object, or None if unavailable.

current_user()

Return the currently authenticated user from the active request.

Returns:

Name Type Description
User

The current Django auth user.

truncate(value, digits)

Truncate a numeric value to a given number of decimal places (no rounding).

Parameters:

Name Type Description Default
value

Numeric value to truncate.

required
digits

Number of decimal places to keep.

required

Returns:

Name Type Description
float

The truncated value.

fix_decimal_product_no(value)

Strip trailing .0 from a numeric string representation.

Parameters:

Name Type Description Default
value

Value to clean.

required

Returns:

Name Type Description
str

Cleaned string.

strip_non_alpha_numeric(string)

Remove all non-alphanumeric characters from a string.

Parameters:

Name Type Description Default
string

Input string to cleanse.

required

Returns:

Name Type Description
str

String with only alphanumeric characters.

to_json(obj)

Serialize an object to a JSON string using its __dict__.

Parameters:

Name Type Description Default
obj

Any object with a __dict__ attribute.

required

Returns:

Name Type Description
str

Pretty-printed JSON string.

from_json(data)

Deserialize a JSON string into nested namedtuples for attribute access.

Parameters:

Name Type Description Default
data

JSON string.

required

Returns:

Name Type Description
namedtuple

Parsed object with attribute-style access.

save_and_return_bytes(wb)

Save an openpyxl Workbook to a temp file and return its bytes.

Parameters:

Name Type Description Default
wb

An openpyxl Workbook instance.

required

Returns:

Name Type Description
bytes

The workbook file contents.

get_bytes_and_delete(file_path)

Read a file as bytes and then delete it.

Parameters:

Name Type Description Default
file_path

Absolute path to the file.

required

Returns:

Name Type Description
bytes

The file contents.

delete_file(file_path)

Delete a file, returning True on success and False on failure.

Parameters:

Name Type Description Default
file_path

Absolute path to the file.

required

Returns:

Name Type Description
bool

True if deleted, False if an error occurred.

rename_file(old_name, new_name)

Rename a file.

Parameters:

Name Type Description Default
old_name

Current file path.

required
new_name

New file path.

required

move_file(source, destination)

Move a file from source to destination.

Parameters:

Name Type Description Default
source

Current file path.

required
destination

Target file path.

required

get_bytes(file_path)

Read and return a file's contents as bytes.

Parameters:

Name Type Description Default
file_path

Absolute path to the file.

required

Returns:

Name Type Description
bytes

The raw file contents.

get_temp_file_path(extn=None)

Generate a unique temp file path under MEDIA_ROOT/tmp/.

Parameters:

Name Type Description Default
extn

Optional file extension (without dot).

None

Returns:

Name Type Description
str

Absolute path to the temp file.

xstr(s, default='')

Convert a value to string, returning a default if None.

Parameters:

Name Type Description Default
s

Value to convert.

required
default

Value to return when s is None. Defaults to ''.

''

Returns:

Name Type Description
str

String representation of s, or default.

unicode_to_string(x)

Convert a unicode value to an ASCII string, ignoring unencodable characters.

Parameters:

Name Type Description Default
x

Value to convert.

required

Returns:

Name Type Description
str

ASCII string.

coalesce(value, replace)

Return value if not None, otherwise return replace.

Parameters:

Name Type Description Default
value

Primary value.

required
replace

Fallback value.

required

Returns:

Type Description

The non-None value.

query_to_dicts(query_string, params=None)

Execute a raw SQL query and yield each row as a dict.

Parameters:

Name Type Description Default
query_string

Raw SQL query string.

required
params

Optional query parameters for parameterized queries.

None

Yields:

Name Type Description
dict

Row data keyed by column name.

query_to_lists(query_string, col_index=None, params=None)

Execute a raw SQL query and yield rows as tuples, or a single column value.

Parameters:

Name Type Description Default
query_string

Raw SQL query string.

required
col_index

If provided, yield only the value at this column index.

None
params

Optional query parameters for parameterized queries.

None

Yields:

Type Description

tuple or value: Full row tuple, or the single column value if col_index is set.

field_html(field, name)

Render a Django form field to its HTML representation.

Parameters:

Name Type Description Default
field

A Django form field instance.

required
name

The field name to use in the rendered HTML.

required

Returns:

Name Type Description
str

The rendered HTML for the field.

get_model_fields(model)

Return a sorted list of (field_name, verbose_name) tuples for a model.

Includes both model fields and properties, excluding common defaults like id, modified, pk, and file.

Parameters:

Name Type Description Default
model

Django model class.

required

Returns:

Type Description

list[tuple[str, str]]: Sorted (name, label) pairs.

get_wb_response_from_bytes(data_bytes, file_name)

Create an HttpResponse for downloading an Excel (.xlsx) file.

Parameters:

Name Type Description Default
data_bytes

The workbook file contents as bytes.

required
file_name

The download file name.

required

Returns:

Name Type Description
HttpResponse

Configured for xlsx download.

get_zip_response_from_bytes(data_bytes, file_name)

Create an HttpResponse for downloading a ZIP file.

Parameters:

Name Type Description Default
data_bytes

The ZIP file contents as bytes.

required
file_name

The download file name.

required

Returns:

Name Type Description
HttpResponse

Configured for zip download.

get_wb_response(wb, file_name)

Save an openpyxl Workbook and return it as an xlsx download response.

Parameters:

Name Type Description Default
wb

An openpyxl Workbook instance.

required
file_name

The download file name.

required

Returns:

Name Type Description
HttpResponse

Configured for xlsx download.

render_to_string_from_source(template_source, context_dict=None)

Render a Django template string with the given context.

Parameters:

Name Type Description Default
template_source

Django template source string.

required
context_dict

Optional context dictionary for rendering.

None

Returns:

Name Type Description
str

The rendered template output.

sum_by_tuple_element_in_list(input_list, decimal_places=None)

Sum values in a list of 2-tuples, grouped by the first element.

Parameters:

Name Type Description Default
input_list

List of (key, value) tuples (e.g. [('Jan 2015', 1544.4), ('Jan 2015', 200.0)]).

required
decimal_places

Optional number of decimal places to round sums to.

None

Yields:

Name Type Description
tuple

(key, summed_value) for each distinct key, preserving insertion order.

median(input_list)

Calculate the median value of a numeric list.

Parameters:

Name Type Description Default
input_list

List of numbers.

required

Returns:

Name Type Description
float

The median value.

mode(input_list)

Return the most frequently occurring value in a list, or 0 if no repeats.

Parameters:

Name Type Description Default
input_list

List of values.

required

Returns:

Type Description

The mode value, or 0 if all values are unique.

math_range(input_list)

Return the range (max - min) of a numeric list.

Parameters:

Name Type Description Default
input_list

List of numbers.

required

Returns:

Name Type Description
float

The range, or 0 for an empty list.

get_subclasses(classes, level=0)

Recursively collect all subclasses of the given class(es).

Parameters:

Name Type Description Default
classes

A class or list of classes.

required
level

Recursion depth (used internally). Defaults to 0.

0

Returns:

Name Type Description
list

All classes including their subclasses at every depth.

get_pdf_response_from_file(pdf, file_name)

Create an HttpResponse for inline PDF display.

Parameters:

Name Type Description Default
pdf

PDF file contents as bytes.

required
file_name

File name (without extension) for the Content-Disposition header.

required

Returns:

Name Type Description
HttpResponse

Configured for inline PDF display.

format_as_currency(value, decimal_precision=2, currency_symbol='$')

Format a numeric value as a currency string with HTML markup.

Negative values are wrapped in a text-danger span with parentheses.

Parameters:

Name Type Description Default
value

Numeric value to format.

required
decimal_precision

Number of decimal places. Defaults to 2.

2
currency_symbol

Currency symbol prefix. Defaults to '$'.

'$'

Returns:

Name Type Description
SafeString

HTML-safe currency string, or the original value if not numeric.

list_to_table(data, table_class='', has_header=False)

Convert a 2D list into an HTML table string.

Parameters:

Name Type Description Default
data

List of lists (rows of cell values).

required
table_class

CSS class(es) for the <table> element.

''
has_header

If True, treat the first row as <thead>.

False

Returns:

Name Type Description
str

HTML table markup.

list_to_ul(iterable, css_class_name='')

Convert an iterable into an HTML unordered list.

Parameters:

Name Type Description Default
iterable

Items to render as <li> elements.

required
css_class_name

Optional CSS class for the <ul>.

''

Returns:

Name Type Description
SafeString

HTML <ul> markup, or empty string if iterable is falsy.

get_count_dict(iterable, by_property=None)

Count occurrences of elements or element properties in an iterable.

Parameters:

Name Type Description Default
iterable

Sequence of items to count.

required
by_property

Optional attribute name (str) or list of attribute names to group by. Supports dict key access as well.

None

Returns:

Name Type Description
dict

Mapping of element (or property value) to count.

Example
get_count_dict(['a', 'b', 'a'])  # {'a': 2, 'b': 1}

ifilter(fn, iterable)

Eager version of filter that returns a list instead of an iterator.

Parameters:

Name Type Description Default
fn

Predicate function.

required
iterable

Items to filter.

required

Returns:

Name Type Description
list

Filtered items.

imap(fn, iterable)

Eager version of map that returns a list instead of an iterator.

Parameters:

Name Type Description Default
fn

Mapping function.

required
iterable

Items to map over.

required

Returns:

Name Type Description
list

Mapped results.

humane_currency(value)

Format a number as a human-readable currency string (e.g. $1.5M).

Parameters:

Name Type Description Default
value

Numeric value to format.

required

Returns:

Name Type Description
str

Abbreviated currency string, or None if value is None.

humane_number(value)

Format a number with magnitude suffix (K, M, B, T).

Parameters:

Name Type Description Default
value

Numeric value to format.

required

Returns:

Name Type Description
str

Abbreviated number string (e.g. '1.5M'), or None if value is None.

group_by_property(iterable, prop=None, prop_fn=None)

Group items by an attribute or a key function.

Parameters:

Name Type Description Default
iterable

Items to group.

required
prop

Attribute name to group by.

None
prop_fn

Callable that extracts the group key from an item.

None

Returns:

Name Type Description
dict

Mapping of group key to list of items.

Example
group_by_property(users, prop='department')

short_uuid()

Generate a short UUID string (last segment of a UUID5).

Returns:

Name Type Description
str

A 12-character hex string.

is_valid_email(email)

Check whether a string is a valid email address.

Parameters:

Name Type Description Default
email

String to validate.

required

Returns:

Name Type Description
bool

True if the email is valid.

chunks(lst, n)

Yield successive n-sized chunks from a list.

Parameters:

Name Type Description Default
lst

The list to split.

required
n

Chunk size.

required

Yields:

Name Type Description
list

Sub-lists of up to n elements.

next_element_in_iterable(iterable, curr)

Return the next element after curr in a list, wrapping around to the start.

Parameters:

Name Type Description Default
iterable

Indexable sequence.

required
curr

Current element to find.

required

Returns:

Type Description

The next element, or the first element if curr is last or not found.

get_csv_bytes(data)

Convert a 2D list to CSV file bytes.

Parameters:

Name Type Description Default
data

List of rows (each row is a list of values).

required

Returns:

Name Type Description
bytes

CSV file contents.

get_json_bytes(data)

Serialize data to pretty-printed JSON file bytes.

Handles datetime and date objects by converting to string.

Parameters:

Name Type Description Default
data

Serializable data structure.

required

Returns:

Name Type Description
bytes

JSON file contents.

get_tz_offset(dt, timezone_name='US/Pacific')

Calculate the UTC offset in hours for a timezone at a given datetime.

Parameters:

Name Type Description Default
dt

Naive datetime to check.

required
timezone_name

Timezone name string. Defaults to 'US/Pacific'.

'US/Pacific'

Returns:

Name Type Description
float

UTC offset in hours.

get_absolute_url(path)

Build an absolute URL for the given path using the current request or settings.

Uses CURRENT_HOST setting if available, otherwise derives from the request.

Parameters:

Name Type Description Default
path

URL path (e.g. '/api/data/').

required

Returns:

Name Type Description
str

Full absolute URL.

pick(input_dict, keys_to_pick)

Return a new dict containing only the specified keys.

Parameters:

Name Type Description Default
input_dict dict

Source dictionary.

required
keys_to_pick []

Keys to include.

required

Returns:

Name Type Description
dict

Filtered dictionary.

omit(input_dict, keys_to_omit)

Return a new dict excluding the specified keys.

Parameters:

Name Type Description Default
input_dict dict

Source dictionary.

required
keys_to_omit []

Keys to exclude.

required

Returns:

Name Type Description
dict

Filtered dictionary.

find(fn, iterable)

Return the first item in iterable that matches the predicate, or None.

Parameters:

Name Type Description Default
fn

Predicate function.

required
iterable

Items to search.

required

Returns:

Type Description

The first matching item, or None.

get_offset_range(minus=0, plus=0)

Generate a list of integer offsets from -minus to +plus, inclusive of 0.

Parameters:

Name Type Description Default
minus

Number of negative offsets.

0
plus

Number of positive offsets.

0

Returns:

Type Description

list[int]: Sorted offset range (e.g. [-2, -1, 0, 1, 2]).

none_safe_get(obj, attr, default=None)

Safely get an attribute from an object that may be None.

Parameters:

Name Type Description Default
obj

Object to access (may be None).

required
attr

Attribute name.

required
default

Value to return if obj is None or attr is missing.

None

Returns:

Type Description

The attribute value, or default.