Core¶
Version: 4.0.0-d
Dependencies
bandit (required) Used to scan SuperDjango for security issues.
semver (required) Used for version management and generating documentation.
Assets¶
Provides access to static files for all other SuperDjango apps and includes resources for programmatically defining JavaScript and CSS.
Component Reference: Assets
Conf¶
Manage settings for SuperDjango.
Component Reference: Conf
Abstract¶
There are a large number of settings which control SuperDjango’s behavior. A means of centralizing and documenting these was desired.
Note
Regarding the choice of django-appconf: Prior to SuperDjango 4, various approaches were used and all suffered from one problem or another. The django-appconf app rather nicely meets the need of centralizing settings, and (as of this writing) has 100% code coverage. However, should it need to be replaced, the source code is relatively straight-forward, and could be adapted and modernized if need be.
-
class
superdjango.conf.
DynamicSettingsWrapper
[source]¶ Bases:
object
Facilitates the acquisition of settings dynamically, by wrapping
settings.py
.This class is automatically instantiated as
SUPERDJANGO
, which makes the following example possible:from superdjango.conf import SUPERDJANGO class Login(LoginView): def get_form_class(self): if SUPERDJANGO.USER_REMEMBER_ME_ENABLED: return AuthenticationForm return DefaultAuthenticationForm
Under the hood,
SUPERDJANGO.USER_REMEMBER_ME_ENABLED
is simply understood asgetattr(settings, "SUPERDJANGO_USER_REMEMBER_ME_ENABLED")
.Note
This is either really clever or really stupid.
-
class
superdjango.conf.
General
(**kwargs)[source]¶ Bases:
appconf.base.AppConf
General settings used by SuperDjango.
To override or set the value of a general setting, add it to your
settings.py
file with theSUPERDJANGO_
prefix. For example:SUPERDJANGO_BASE_TEMPLATE = "base_site.html"
-
AJAX_MODULE_NAME
= 'ajax'¶ The name of the module (or package) that contains code for automated integration of AJAX views.
-
API_MODULE_NAME
= 'api'¶ The name of the module (or package) that contains code for automated Django REST Framework integration.
-
BASE_TEMPLATE
= 'base.html'¶ The base template to extend.
-
DATA_PATH
= None¶ The path to data stored for the project or its apps.
-
DATETIME_MASK
= '%b %d, %Y %I:%M%p'¶ The default strftime() <https://docs.python.org/3.7/library/datetime.html#strftime-strptime-behavior>_ specification which should be used to format datetime objects.
-
DATE_MASK
= '%b %d, %Y'¶ The default strftime() <https://docs.python.org/3.7/library/datetime.html#strftime-strptime-behavior>_ specification which should be used to format dates.
-
FORM_DEBUG
= False¶ Indicates form debugging is enabled. Note: This must be included in the context; see
superdjango.context_processors.settings_in_context
.
-
HELP_ENABLED
= True¶ Used internally in SuperDjango UI templates. Indicates whether the support application is enabled.
-
MARKDOWN_EXTENSIONS
= ['extra']¶ The extensions to be enabled when working with Markdown content.
-
PAGINATION_LIMIT
= 10¶ The default number of records to show in a list view.
-
REDIRECT_KEY
= 'next'¶ The name of the GET key used to send a user to a URL after logging in.
-
SCHEDULER_MODULE_NAME
= 'scheduler'¶ The module name for apps wishing to contribute jobs to
superdjango.contrib.scheduler
.
-
SCHEDULER_PATH
= '/Users/shawn/Work/superdjango4/tests/example_project/source/../config/scheduler.ini'¶ The path to the scheduled jobs configuration.
-
SSL_REQUIRED
= False¶ Indicates whether UI views must be served via a secure connection. By default, SSL is required except for development.
-
UPPERS
= ['api', 'cname', 'css', 'hr', 'html', 'id', 'imap', 'inc', 'llc', 'pop3', 'purl', 'rss', 'sla', 'sms', 'smtp', 'ssl', 'tcp', 'tls', 'url', 'vip', 'xml']¶ The default list of strings to be converted to upper case by SuperDjango’s
title()
shortcut.
-
USE_CDN
= False¶ Indicates that SuperDjango’s CDN should be used for static files, when available. The default is to use bundled files when
DEBUG
isTrue
and the preferred CDN of the resource whenDEBUG
isFalse.
-
WEBMASTER_EMAIL
= 'webmaster@superdjango.com'¶ The email address from which site email will be sent.
-
WEBMASTER_NAME
= 'Webmaster'¶ The name of the site’s webmaster.
-
-
class
superdjango.conf.
Internationalization
(**kwargs)[source]¶ Bases:
appconf.base.AppConf
-
COUNTRY_CHOICES
= None¶ A choice list of ISO-3166-1 codes and country names.
-
DEFAULT_COUNTRY_CODE
= None¶ The default country code to use for
CountryField
.
-
DEFAULT_CURRENCY_CODE
= None¶ The default currency code to use for
CurrencyField
.
-
TIMEZONE_CHOICES
= None¶ A list of choices for time zone form fields.
-
TIMEZONE_KEY
= 'django_time_zone'¶ The name of the session key used to store the user’s time zone.
-
-
class
superdjango.conf.
Support
(**kwargs)[source]¶ Bases:
appconf.base.AppConf
Configuration for
contrib.support
.-
MARKDOWN_EXTENSIONS
= ['extra']¶ A list of Markdown extensions to use when rendering support docs.
-
PATH
= '/Users/shawn/Work/superdjango4/tests/example_project/source/../help'¶ The path to support content.
-
REQUIRES_LOGIN
= True¶ Indicates whether accessing support content requires an authenticated users.
-
SEARCH_LOG_RESULTS
= True¶ Indicates search results should be logged. Helps improve the search catalog.
-
SEARCH_TERMS
= []¶ A list of terms that may be used to build the search catalog.
-
URL
= '/help/'¶ The URL where support content may be accessed.
-
-
class
superdjango.conf.
User
(**kwargs)[source]¶ Bases:
appconf.base.AppConf
User-related settings provided by SuperDjango.
-
AUTO_CREATE_PROFILE
= False¶ Indicates that a user profile instance should be created, if possible, when one does not already exist. Consider setting this to
False
while settingauto_create
toTrue
on yourProfileUpdate
view. See profile views for an example.
-
IMPERSONATION_ENABLED_FOR_GROUPS
= None¶ Indicates user impersonation is available to users belonging to any of the group names in the list.
-
IMPERSONATION_ENABLED_FOR_STAFF
= True¶ Indicates user impersonation is available to
is_staff
users.
-
IMPERSONATION_MODEL
= None¶ The model used to log impersonation history.
-
INVITATIONS_ENABLED
= False¶ Indicates whether users are allowed to invite other users.
-
INVITATION_EXPIRATION
= 864000¶ The number of days before a user invitation expires.
-
INVITATION_GROUPS
= None¶ A list of groups (names) into which a user will be placed upon accepting an invitation.
-
INVITATION_LIMIT
= None¶ The number of invitations that a user may send.
-
INVITATION_MODEL
= None¶ The model to use for user invitations.
-
LOGIN_EXCLUDED_URLS
= None¶ Include URLs that do not (or should not) require a log in when
LoginRequiredMiddleware
is enabled. Django’sLOGIN_URL
is added automatically.
-
LOGIN_REDIRECT_URL
= '/accounts/profile/'¶ The URL to which users are redirected (by default) after a successful login.
-
LOGIN_REQUIRED
= True¶ Indicates that an authenticated user is the default for accessing views.
-
LOGOUT_REDIRECT_URL
= '/'¶ The URL to which users are redirected after logging out.
-
MAX_LOGIN_ATTEMPTS
= None¶ The maximum number of login attempts (int) before a user account is locked.
-
MAX_LOGIN_MINUTES
= None¶ The number of minutes (int) between max login attempts.
-
MAX_PASSWORD_RESET_ATTEMPTS
= 3¶ The maximum number of password reset attempts (int) before a user account is locked.
-
MAX_PASSWORD_RESET_MINUTES
= 30¶ The number of minutes (int) between max password reset attempts.
-
ORDER_USERS_BY
= 'first_name'¶ The field name by which to order user lists.
-
PASSWORD_RESET_LOGGING_ENABLED
= False¶ Indicates logging should be enabled for password reset attempts. Requires
PASSWORD_RESET_MODEL
.
-
PASSWORD_RESET_LOGIN
= False¶ Indicates whether the user should be logged in after a password reset has been confirmed.
-
PASSWORD_RESET_MODEL
= None¶ The model used for logging password reset attempts in
app_label.ModelName
format.
-
PASSWORD_RESET_USERNAME_ENABLED
= False¶ When
True
, the reset lookup will also attempt to find a given user name if one has been given.
-
PROFILE_MODEL
= None¶ The model used for user profile in
app_label.ModelName
format.
-
REDIRECT_TO_CHOICES
= None¶ A list of Django choices used for the
redirect_to
dropdown of theProfileModel
.
-
REGISTRATION_AFTER_URL
= None¶ The URL to which a visitor will be directed after submitting a registration request.has been created. The default is the
RegistrationSubmitted
view.
-
REGISTRATION_ALLOWED_DOMAINS
= None¶ A list of the email domains that are recognized (allowed) for self-registration.
-
REGISTRATION_APPROVAL_HOURS
= 48¶ The average number of hours (int) needed to manually approve registrations when approval is required. This may be displayed to users after sign-up.
-
REGISTRATION_APPROVAL_REQUIRED
= False¶ Indicates whether new registrations require admin approval.
-
REGISTRATION_AUTO_LOGIN
= True¶ Indicates a user should be logged in upon a successful (completed) registration.
-
REGISTRATION_BEFORE_URL
= None¶ The URL to which a visitor will be directed before a registration may be requested. For example, this could be used to direct the user to a Terms and Conditions page. The page should include a link to the
RegistrationCreate
view that includesreg=1
in the URL.
-
REGISTRATION_BODY
= None¶ The body of the email message sent to visitors upon new user account registration. If omitted, the standard template is used.
-
REGISTRATION_CONFIRMATION_BODY
= None¶ The body of the email message sent to visitors upon new user account registration. If omitted, the standard template is used.
-
REGISTRATION_CONFIRMATION_REQUIRED
= True¶ Indicates whether new user registrations require user confirmation. This invokes the Confirmation Workflow.
-
REGISTRATION_CONFIRMATION_SUBJECT_LINE
= None¶ The subject line of the email message sent to visitors upon new user account registration. If omitted, the standard template is used.
-
REGISTRATION_DECLINED_BODY
= None¶ The body of the email message sent when a registration is declined.
REGISTRATION_APPROVAL_REQUIRED
must beTrue
. If omitted, the default template is used.
-
REGISTRATION_DECLINED_SUBJECT
= None¶ the subject line of the declined registration email. If omitted, the default template is used.
-
REGISTRATION_DISABLED_MESSAGE
= None¶ The message to display when registration is currently disabled.
-
REGISTRATION_DISABLED_URL
= '/'¶ The URL to which a visitor will be directed upon attempting to register an account when registration is currently disabled. This defaults to the
RegistrationDisabled
view if enabled.
-
REGISTRATION_ENABLED
= False¶ Allows visitors to sign up for user accounts.
-
REGISTRATION_EXPIRES_AFTER_DAYS
= 7¶ The number of days (int) a registration remains valid after it is sent.
-
REGISTRATION_FORM
= None¶ The form to use for user registrations.
-
REGISTRATION_GROUPS
= None¶ A list of group names to which the user should be assigned upon successful (completed) registration.
-
REGISTRATION_MODEL
= None¶ The model (in the form of
app_label.ModelName
) to use when registration approvals are required.
-
REGISTRATION_OPEN_DATE
= None¶ The date upon which user registration will again be allowed.
-
REGISTRATION_OPEN_URL
= None¶ The URL where a user may be notified (or request notification) when registration is available. This might be a page or a sign-up form.
-
REGISTRATION_REDIRECT_URL
= None¶ the URL to which a new user will directed after confirming a registration. The default is the
RegistrationComplete
view.
-
REGISTRATION_SALT
= 'registration'¶ The salt to use for creating activation keys.
-
REGISTRATION_SUBJECT_LINE
= None¶ The subject line of the email message sent to visitors upon new user account registration. If omitted, the standard template is used.
-
REMEMBER_ME_ENABLED
= False¶ Indicates whether “remember me” is presented on the login form.
-
REMEMBER_ME_SECONDS
= 2592000¶ The number of seconds (int) a user’s session should last when the remember me option is selected. Defaults to 30 days.
-
SSO_LINK_USER
= False¶ When using the
multisso
app, this provides the option of connecting the user account with the record of the SSO provider.
-
SSO_SERVICE_URL
= None¶ This is the service URL sent to the provider. The provider may need to be configured to accept this URL. When
DEBUG
isTrue
, it defaults to the development URL. Otherwise anImproperlyConfigured
is raised if this value is not defined.
-
Context Processors¶
Commonly needed processing that doesn’t necessarily fit within a specific app.
Component Reference: Context Processors
Install¶
Add the desired context processor to template options. For example:
TEMPLATES = [
{
# ...
'OPTIONS': {
'context_processors': [
# ...
'superdjango.context_processors.settings_in_context',
# ...
],
},
},
]
-
superdjango.context_processors.
settings_in_context
(request)[source]¶ Insert certain Django settings into the context.
- Parameters
request – The request instance is not used.
- Type
request: object
- Return type
dict
To identify the settings to be included in the request context, use the
SETTINGS_IN_CONTEXT
in yoursettings.py
file.COPYRIGHT_NAME = "Pleasant Tents, LLC" MENU_ITEMS = [ ("home", "Home"), ("dashboard", "Dashboard"), ("profile", "Profile"), ] SITE_TITLE = "Example Site" SUPERDJANGO_SETTINGS_IN_CONTEXT = [ "COPYRIGHT_NAME", "MENU_ITEMS", "SITE_TITLE", ]
Constants¶
Constants that may be used across SuperDjango and (optionally) your project.
Component Reference: Constants
Forms¶
Forms, fields, and widgets used across SuperDjango.
Component Reference: Forms
fields¶
-
class
superdjango.forms.fields.
FullNameChoiceField
(queryset, *, empty_label='---------', required=True, widget=None, label=None, initial=None, help_text='', to_field_name=None, limit_choices_to=None, **kwargs)[source]¶ Bases:
django.forms.models.ModelChoiceField
If available, uses the full name of the user for the dropdown instead of the user name.
Usage
In your form:
from django.contrib.auth import get_user_model user_model = get_user_model() class MyModelForm(ModelForm): requested_by = FullNameChoiceField( queryset=user_model.objects.filter(is_staff=True), label=_("requested by") )
forms¶
-
class
superdjango.forms.forms.
EAVFormMixin
(*args, **kwargs)[source]¶ Bases:
object
A mixin for implementing an entity-attribute-value model with a standard model form.
-
attribute_model
= None¶ The concrete model used to define the available custom attributes.
-
attribute_name
= 'attribute'¶ The name of the field used to identify the attribute model.
-
entity_name
= None¶ The field name of the model to which extra attributes are added via the
value_model
.
-
get_attribute_model
()[source]¶ Get the model class used to define available attributes.
- Return type
BaseType[superdjango.db.eav.models.AttributeModel]
- Raise
IMustBeMissingSomething
-
get_attribute_name
()[source]¶ Get the field name used to identify the attribute model. Defaults to
attribute
.- Return type
str
-
get_attribute_value
(attribute)[source]¶ Get the value instance for the given attribute and current instance.
- Parameters
attribute (BaseType[superdjango.db.eav.models.AttributeModel]) – The name of the attribute whose value is to be returned.
- Return type
BaseType[superdjango.db.eav.models.ValueModel] | None
- Returns
The value record instance or
None
if no value has been provided.
-
get_attributes
()[source]¶ Get the attributes to be used in the form.
- Return type
django.db.models.QuerySet
- Returns
A queryset using
attribute_model
.
Note
This method is called during
__init__()
.Tip
By default all enabled attributes are returned. If you need to, you may filter these by overriding this method.
-
get_custom_fields
()[source]¶ Get custom (possibly bound) fields for display in form output.
- Return type
list
-
get_entity_name
()[source]¶ Get the field name of the object to which extra attributes are attached.
- Return type
str
- Raise
IMustBeMissingSomething
-
get_value_model
()[source]¶ Get the model class used to define attribute values.
- Return type
BaseType[superdjango.db.eav.models.ValueModel]
- Raise
IMustBeMissingSomething
-
value_model
= None¶ The concrete model used to store values for custom attributes.
-
-
class
superdjango.forms.forms.
EAVModelForm
(*args, **kwargs)[source]¶ Bases:
superdjango.forms.forms.EAVFormMixin
,django.forms.models.ModelForm
An implementation of entity-value-attribute model form.
-
class
superdjango.forms.forms.
RequestEnabledModelForm
(fieldsets=None, request=None, tabs=None, **kwargs)[source]¶ Bases:
django.forms.models.ModelForm
Incorporates the current request and enables fieldset/tab support. Used by SuperDjango UI.
-
__init__
(fieldsets=None, request=None, tabs=None, **kwargs)[source]¶ Add support for fieldsets and current request.
-
property
fieldsets
¶ Alias for
get_fieldsets()
.
-
property
has_fieldsets
¶ Indicates whether the form has defined fieldsets.
- Return type
bool
-
property
has_tabs
¶ Indicates whether the form has defined tabs.
- Return type
bool
-
property
tabs
¶ Alias for
get_tabs()
.
-
-
class
superdjango.forms.forms.
SearchForm
(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None)[source]¶ Bases:
django.forms.forms.Form
Standard search form, used by UI search views.
widgets¶
-
class
superdjango.forms.widgets.
AjaxUploadWidget
(attrs=None)[source]¶ Bases:
django.forms.widgets.ClearableFileInput
A file widget that provides support for AJAX uploads.
-
class
superdjango.forms.widgets.
ChooserWidget
(attrs=None, choices=())[source]¶ Bases:
django.forms.widgets.Select
A widget that may be used to transform a select into a chooser.
-
class
superdjango.forms.widgets.
CodeEditorWidget
(attrs=None)[source]¶ Bases:
django.forms.widgets.Textarea
A widget for producing a code editor.
-
class
superdjango.forms.widgets.
ColorPickerWidget
(attrs=None)[source]¶ Bases:
django.forms.widgets.TextInput
A widget that supports a color picker.
-
property
media
¶ Return the form media for the color picker resource.
-
property
-
class
superdjango.forms.widgets.
MarkdownWidget
(attrs=None, options=None)[source]¶ Bases:
django.forms.widgets.Textarea
A widget for creating a Markdown editor.
Base on SimpleMDE.
-
__init__
(attrs=None, options=None)[source]¶ Initialize the widget. The
options
parameter is for SimpleMDE options.
-
property
media
¶ Support for standard Django implementation.
-
-
class
superdjango.forms.widgets.
ReadOnlyWidget
(attrs=None)[source]¶ Bases:
django.forms.widgets.Input
Display only the value of the field.
Environment¶
Load configuration variables from an INI file.
Component Reference: Environment
library¶
-
class
superdjango.env.library.
Env
(path, autoload=True)[source]¶ Bases:
object
The Env class assists with loading environment variables from an INI file.
The file may be located anywhere that is accessible for reading by the user that executes the Python process.
; All variables defined in the environment section are available as attributes of the Env instance. For example, ; env.debug [environment] debug = no name = live [database] host = db.example.com name = example_com password = dbpassword user = example_com [mailgun] api_key = mailgunapikey enabled = yes sender_domain = mg.example.com [secret] key = somesupersecretkey
In your
settings.py
file:from superdjango.env import Env env = Env("env.ini") SECRET_KEY = env.secret.key if env.name == "live": DEBUG = False else: DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': env.database.host, 'NAME': env.database.name, 'PASSWORD': env.database.password, 'USER': env.database.user, } } # ... and so on ...
-
__init__
(path, autoload=True)[source]¶ Initialize the environment.
- Parameters
path (str) – The path to the INI file.
autoload (bool) – Automatically load the file upon instantiation. See
load()
.
-
get
(section, default=None, key=None)[source]¶ Get a section, and optionally a variable within that section.
- Parameters
section (str) – The section name.
default – The default value if the key does not exist.
key (str) – The name of the variable to get from the section.
-
Exceptions¶
Exceptions for speed, convenience, and humor.
Component Reference: Exceptions
-
exception
superdjango.exceptions.
DeeplyDisturbingError
[source]¶ Bases:
Exception
Indicates something is very (very) wrong with core, or “deep” functionality – and we don’t really know why.
-
exception
superdjango.exceptions.
IMustBeMissingSomething
(class_name, attribute_name, method_name=None)[source]¶ Bases:
django.core.exceptions.ImproperlyConfigured
Indicates a view is missing an attribute or method definition.
-
__init__
(class_name, attribute_name, method_name=None)[source]¶ Issue the error.
- Parameters
class_name (str) – The name of the class with the missing attribute or method.
attribute_name (str) – The name of the missing attribute.
method_name (str) – The name (without the parentheses) of the method that calls the attribute.
-
-
exception
superdjango.exceptions.
ModelAlreadyRegistered
(model)[source]¶ Bases:
Exception
Indicates a model has already been registered with a
SiteUI
instance.
-
exception
superdjango.exceptions.
NoUserInRequest
[source]¶ Bases:
django.core.exceptions.ImproperlyConfigured
This error occurs when a request has no user attribute.
-
exception
superdjango.exceptions.
NoViewForYou
[source]¶ Bases:
Exception
Occurs when a view or viewset encounters errors with automatic generation of the view or URL.
-
exception
superdjango.exceptions.
ThisShouldNeverHappen
[source]¶ Bases:
Exception
Indicates an application state that should never actually occur.
HTML¶
An app providing resources for working with HTML in a reasonably abstract manner.
Component Reference: HTML
bootstrap4¶
Support for templates based on Twitter Bootstrap 4. To use, add superdjango.html.frameworks.bootstrap4
to
INSTALLED_APPS
.
foundation6¶
Support for templates based on Foundation 6. To use, add superdjango.html.frameworks.foundation6
to
INSTALLED_APPS
.
uikit3¶
Support for templates based on UI Kit 3. To use, add superdjango.html.frameworks.uikit3
to
INSTALLED_APPS
.
library¶
-
class
superdjango.html.library.
Breadcrumb
(text, url)[source]¶ Bases:
object
Helper class that ensures an object has the required attributes.
-
class
superdjango.html.library.
Breadcrumbs
[source]¶ Bases:
object
Collect objects to be displayed as breadcrumbs.
-
add
(text, url, pattern_args=None, pattern_kwargs=None, namespace=None)[source]¶ Add a breadcrumb to the list.
- Parameters
text (str) – The breadcrumb label/text.
url (str) – The URL or pattern name.
pattern_args (list) – Pattern arguments when the URL is given as a pattern name.
pattern_kwargs (dict) – Pattern keyword arguments when the URL is given as a pattern name.
namespace (str) – The application namespace for the URL when given as a pattern name.
- Return type
-
insert
(index, text, url, pattern_args=None, pattern_kwargs=None, namespace=None)[source]¶ Insert a breadcrumb in the list.
- Parameters
index (int) – The index of the new breadcrumb..
text (str) – The breadcrumb label/text.
url (str) – The URL or pattern name.
pattern_args (list) – Pattern arguments when the URL is given as a pattern name.
pattern_kwargs (dict) – Pattern keyword arguments when the URL is given as a pattern name.
namespace (str) – The application namespace for the URL when given as a pattern name.
- Return type
-
-
class
superdjango.html.library.
Column
(name, help_text=None, label=None, **kwargs)[source]¶ Bases:
superdjango.html.library.base.Element
A column (header) in an HTML table.
-
__init__
(name, help_text=None, label=None, **kwargs)[source]¶ Initialize the column.
- Parameters
name (str) – The programmatic name of the column. For example, the field name.
help_text (str) – Help text for the column.
label (str) – The column label. If omitted, the name is converted into a label.
-
property
title
¶ Get the column label. Alias for
label
.
-
-
class
superdjango.html.library.
Element
(tag, classes=None, close_tag=None, content='', **kwargs)[source]¶ Bases:
object
Base class for HTML elements.
-
__init__
(tag, classes=None, close_tag=None, content='', **kwargs)[source]¶ Initialize the element.
- Parameters
tag (str) – The HTML tag that opens the element.
classes (list | str | tuple) – A list of CSS classes to be applied to the element.
close_tag (str) – The HTML tag that closes the element.
content (str) – The content (inner HTML or text) of the element.
Additional keyword arguments are treated as attributes of the element.
-
property
attributes
¶ Get the flattened attributes for the element.
- Return type
str
-
get_content
()[source]¶ Get the content of the tag.
- Return type
str
Note
Child classes may re-implement this as needed.
-
-
class
superdjango.html.library.
FieldGroup
(*fields, label=None, size=None)[source]¶ Bases:
object
A group of fields.
-
class
superdjango.html.library.
Fieldset
(legend, fields=None, **kwargs)[source]¶ Bases:
superdjango.html.library.base.Element
A fieldset within a form.
-
__init__
(legend, fields=None, **kwargs)[source]¶ Initialize the element.
- Parameters
tag (str) – The HTML tag that opens the element.
classes (list | str | tuple) – A list of CSS classes to be applied to the element.
close_tag (str) – The HTML tag that closes the element.
content (str) – The content (inner HTML or text) of the element.
Additional keyword arguments are treated as attributes of the element.
-
-
class
superdjango.html.library.
Row
(data, **kwargs)[source]¶ Bases:
superdjango.html.library.base.Element
A row in an HTML table.
-
__init__
(data, **kwargs)[source]¶ Initialize the row.
- Parameters
data (list | tuple) – The data to be included in the row.
-
property
data
¶ Alias for
_data
.
-
-
class
superdjango.html.library.
Table
(caption=None, columns=None, rows=None, **kwargs)[source]¶ Bases:
superdjango.html.library.base.Element
An HTML table.
-
__init__
(caption=None, columns=None, rows=None, **kwargs)[source]¶ Initialize the table.
- Parameters
caption (str) – Optional caption for the table.
columns (list[superdjango.html.library.Column]) – The columns to be included in the table.
rows (list[superdjango.html.library.Row]) – The rows to be included in the table.
-
column
(name, help_text=None, label=None, **kwargs)[source]¶ Add a column to the table.
- Parameters
name (str) – The programmatic name of the column. For example, the field name.
help_text (str) – Help text for the column.
label (str) – The column label. If omitted, the name is converted into a label.
- Return type
-
templatetags¶
html_tags¶
Get the value of an attribute from a given instance.
- Parameters
instance – The instance.
name (str) – The attribute name.
Get the template for a given field instance.
Get the type of field for the given field instance.
An alias for Django’s
flatatt
because I can never remember that name for some reason. Although, I probably will now since I’ve created an alias for it.
Get the Gravatar for the given user.
Get HTML for the given path.
Get the value from the given index.
- Parameters
obj (list | tuple) – A list or tuple.
index (int) – The index to return.
Get the type of field (in lower case).
Indicates whether a form field is required.
Replace new lines with a br tag.
Replace a string.
Return the request query string.
lazy_loader¶
The lazy loader is a replacement for the load
template tag that allows template tags to be conditionally loaded and
used. It is inspired by django-friendly-tag-loader, but is intentionally much less robust.
See also: https://stackoverflow.com/q/7835155/241720
Generic templates and templates provided by contrib apps utilize lazy loader to conditionally load and snippet tags.
Determine if a given tag exists before calling it.
{% if_tag_exists sidebar_items %} {% sidebar_items page=page %} {% else %} No sidebar for you! {% endif_tag_exists %}
Load template tag library if it exists.
{% load lazy_loader %} {% lazy_load support_tags %}
markdown_tags¶
Output a string as markdown. Mark safe occurs automatically.
shortcuts¶
Shortcuts, especially for working with Django templates in an ad-hoc manner.
-
superdjango.html.shortcuts.
parse_string
(string, context)[source]¶ Parse a string as a Django template.
- Parameters
string (str) – The name of the template.
context (dict) – Context variables.
- Return type
str
utils¶
-
class
superdjango.html.utils.
HTMLFramework
[source]¶ Bases:
object
A utility class which encapsulates functionality for identifying the current HTML framework.
-
classmethod
get_path
(*parts, prefix='html')[source]¶ As with
path()
, but joins the given parts relative to the path of the HTML framework.
-
classmethod
path
(prefix='html')[source]¶ Get the path to the framework. See
get_html_path()
.
-
classmethod
-
superdjango.html.utils.
get_field_template
(instance)[source]¶ Get the template to use for a given field instance.
- Parameters
instance (BaseType[Field]) – The field instance to be checked.
- Return type
str
-
superdjango.html.utils.
get_field_type
(instance)[source]¶ Get the type of field for a given instance.
- Parameters
instance (Type[Field]) – The field instance to be checked.
- Return type
str
-
superdjango.html.utils.
get_html_framework
()[source]¶ Get the framework to use for rendering standard HTM Gel templates.
- Return type
str
- Raise
ImproperlyConfigured
-
superdjango.html.utils.
get_html_path
(prefix='html')[source]¶ Get the path to standard HTM Gel templates.
- Parameters
prefix (list | str | tuple) – The prefix or starting point of the path. This may be given as
["superdjango", "ui"]
or["superdjango", "views"]
or a custom prefix to use templates that you’ve created.- Return type
str
- Raise
ImproperlyConfigured
Patterns¶
Utilities and backends for file storage.
Component Reference: Patterns
constants¶
The PATTERN_
constants work with Django’s path()
conversion while the REGEX_
constants work with
re_path()
.
-
superdjango.patterns.constants.
PATTERNS
= {'lookup': '<str:{lookup}>', 'md5': '<md5:hash>', 'path': '<path:path>', 'pk': '<int:pk>', 'slug': '<slug:slug>', 'uuid': '<uuid:uuid>', 'version': '<version:version>', 'year': '<yyyy:year>'}¶ A dictionary of pattern values.
-
superdjango.patterns.constants.
PATTERN_LOOKUP
= '<str:{lookup}>'¶ PATTERN_LOOKUP
may be used for all other lookup fields, but cannot be used as is. The lookup keyword must be formatted in order to use the pattern:from superdjango.patterns import PATTERN_LOOKUP class TaskList(ListView): lookup_field = PATTERN_LOOKUP.format(**{'lookup': "my_unique_field_name"}) # ...
-
superdjango.patterns.constants.
PATTERN_MD5
= '<md5:hash>'¶ A pattern which matches an MD5 hex digest string. The MD5 converter must be registered to use this pattern.
# main/urls.py from django.urls import register_converter from superdjango.patterns import PATTERN_MD5, MD5Converter register_converter(MD5Converter, "md5")
-
superdjango.patterns.constants.
PATTERN_PATH
= '<path:path>'¶ Match any non-empty string.
-
superdjango.patterns.constants.
PATTERN_PK
= '<int:pk>'¶ The standard pattern for classed-based views, assuming the primary key of the model is used for the lookup field.
-
superdjango.patterns.constants.
PATTERN_SLUG
= '<slug:slug>'¶ Used when the lookup field is a
SlugField
namedslug
. You should ensure that the slug field is unique.
-
superdjango.patterns.constants.
PATTERN_UUID
= '<uuid:uuid>'¶ A regex pattern that may be used when the lookup field is a
UUIDField
nameduuid
.
-
superdjango.patterns.constants.
PATTERN_VERSION
= '<version:version>'¶ Matches a semantic versioning string. The version converter must be registered to use this pattern.
# main/urls.py from django.urls import register_converter from superdjango.patterns import PATTERN_VERSION, VersionConverter register_converter(VersionConverter, "version")
-
superdjango.patterns.constants.
PATTERN_YEAR
= '<yyyy:year>'¶ A pattern which matches a four digit year. The corresponding converter must be registered.
# main/urls.py from django.urls import register_converter from superdjango.patterns import PATTERN_YEAR, FourDigitYearConverter register_converter(FourDigitYearConverter, "yyyy")
-
superdjango.patterns.constants.
REGEX_LOOKUP
= '(?P<{lookup}>[^/]+)'¶ REGEX_LOOKUP
may be used for all other lookup fields, but cannot be used as is. The lookup keyword must be formatted in order to use the pattern:from superdjango.patterns import REGEX_LOOKUP context = {'lookup': "my_unique_field_name"} lookup = REGEX_LOOKUP.format(**context)
-
superdjango.patterns.constants.
REGEX_PASSWORD_RESET
= '(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})'¶ The standard pattern for password reset variables.
-
superdjango.patterns.constants.
REGEX_PATTERNS
= {'lookup': '(?P<{lookup}>[^/]+)', 'password': '(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', 'pk': '(?P<pk>\\d+)', 'slug': '(?P<slug>[\\w-]+)', 'uuid': '(?P<uuid>[\\w-]+)', 'version': '(?P<version>[\\d\\w.-]+)'}¶ A collection of regex patterns that must be processed with
re_path
.
-
superdjango.patterns.constants.
REGEX_PK
= '(?P<pk>\\d+)'¶ The standard pattern for classed-based views, assuming the primary key of the model is used for the lookup field.
-
superdjango.patterns.constants.
REGEX_SLUG
= '(?P<slug>[\\w-]+)'¶ Used when the lookup field is a
SlugField
namedslug
. You should ensure that the slug field is unique.
-
superdjango.patterns.constants.
REGEX_UUID
= '(?P<uuid>[\\w-]+)'¶ A regex pattern that may be used when the lookup field is a
UUIDField
nameduuid
.
-
superdjango.patterns.constants.
REGEX_VERSION
= '(?P<version>[\\d\\w.-]+)'¶ Matches a semantic versioning string.
converters¶
Additional path converters.
-
class
superdjango.patterns.converters.
FourDigitYearConverter
[source]¶ Bases:
object
Path converter for a year in YYYY format. Straight from the Django documentation.
library¶
-
class
superdjango.patterns.library.
ModelPattern
(model, view, list_path='', lookup_field=None, lookup_key=None, name=None, namespace=None, prefix=None, regex=None, verb=None)[source]¶ Bases:
object
A helper class for encapsulating data for model views to derive the necessary components for automatic URL definition.
Primarily used by the UI package to automatically generate URLs for the user interface. However, programmatic use is also possible:
update = ModelPattern( Project, ProjectUpdate, lookup_field="uuid" )
-
__init__
(model, view, list_path='', lookup_field=None, lookup_key=None, name=None, namespace=None, prefix=None, regex=None, verb=None)[source]¶ Initialize a view pattern.
- Parameters
model (class) – The model class. This is used only during instantiation.
view (class) – The view class.
list_path (str) – The part of the path that represents the model’s list view. This defaults to an empty string, but may be given if something else will live at the “index” of the model’s views. For example,
list_path="index"
orlist_path="list"
.lookup_field (str) – The name of the field used to uniquely identify a record. This is required for any view that resolves to a specific record. Default:
uuid
.name (str) – If given, this is used as the pattern name of the view instead of composing the name using pattern attributes.
namespace (str) – The namespace in which the view operates.
prefix (str) – The prefix of the URL. For example, the model’s
app_label
.regex (str) – A regular expression used to identify the view in URLs. This is optional.
verb (str) – The name (verb) of the view. For example: “create”, “list”, “detail”, etc.
Important
lookup_field
should only be provided for views that actually require identifying a specific record.
-
get_name
(namespace=None)[source]¶ Get the name of the view.
- Parameters
namespace (str) – The namespace in which the view operates.
- Return type
str
-
property
name
¶ Alias for
get_name()
.
-
property
path
¶ Alias for
get_path()
.
-
property
regex
¶ Alias for
get_regex()
.
-
-
class
superdjango.patterns.library.
Pattern
(name, namespace=None)[source]¶ Bases:
object
A generic pattern for representing a view.
-
__init__
(name, namespace=None)[source]¶ Initialize the pattern.
- Parameters
name (str) – The pattern name.
namespace (str) – The namespace in which the pattern exists.
-
Sessions¶
Work with Django sessions using an object-oriented interface.
Component Reference: Sessions
library¶
-
class
superdjango.sessions.library.
Session
(request, prefix=None)[source]¶ Bases:
object
A simplistic helper for working with session variables in a sane way.
-
__init__
(request, prefix=None)[source]¶ Initialize session interface.
- Parameters
request (django.http.request.HttpRequest) – The current request.
prefix (str) – The variable name prefix, if any.
-
get
(name, default=None)[source]¶ Get a session variable, automatically prefixing the name.
- Parameters
name (str) – The variable name.
default – The value to use if no value is already set.
-
Shortcuts¶
A library of functions and classes that span Django’s MVT framework.
Component Reference: Shortcuts
library¶
Library of shortcuts.
-
class
superdjango.shortcuts.library.
CompareQuerySet
(qs1, qs2)[source]¶ Bases:
object
Compare two querysets to see what’s been added or removed.
-
__init__
(qs1, qs2)[source]¶ Initialize the comparison.
- Parameters
qs1 (django.db.models.QuerySet) – The primary or “authoritative” queryset.
qs2 (django.db.models.QuerySet) – The secondary queryset.
-
get_added
()[source]¶ Get the primary keys of records in qs2 that do not appear in qs1.
- Return type
list
-
-
superdjango.shortcuts.library.
copy_model_instance
(instance)[source]¶ Copy an instance of a model.
- Parameters
instance (Model) – The model instance to be copied.
- Returns
Returns a copy of the model instance.
Tip
The new instance has not been saved to the database. Also, reference fields must be manually recreated using the original instance.
-
superdjango.shortcuts.library.
get_app_modules
(name)[source]¶ Yields tuples of
(app_name, module)
for each installed app that includes the given module name.- Parameters
name (str) – The module name.
-
superdjango.shortcuts.library.
get_model
(dotted_path, raise_exception=True)[source]¶ Get the model for the given dotted path.
- Parameters
dotted_path (str) – The
app_label.ModelName
path of the model to return.raise_exception (bool) – Raise an exception on failure.
-
superdjango.shortcuts.library.
get_setting
(name, default=None)[source]¶ Get the value of the named setting from the
settings.py
file.- Parameters
name (str) – The name of the setting.
default – The default value.
-
superdjango.shortcuts.library.
get_setting_with_prefix
(name, default=None, prefix='SUPERDJANGO')[source]¶ Get the value of the named setting from the
settings.py
file.- Parameters
name (str) – The name of the setting.
default – The default value.
prefix (str) – The setting prefix.
-
superdjango.shortcuts.library.
get_user_name
(user)[source]¶ Get the full name of the user, if available, or just the value of the username field if not.
- Parameters
user – The user instance.
- Return type
str | None
- Raises
AttributeError
if a custom user model has been implemented without aget_full_name()
method.
Tip
It is safe to call this function at runtime where user is
None
.
-
superdjango.shortcuts.library.
has_o2o
(instance, field_name)[source]¶ Test whether a OneToOneField is populated.
- Parameters
instance (object) – The model instance to check.
field_name (str || unicode) – The name of the one to one field.
- Return type
bool
This is the same hasattr()`, but is more explicit and easier to remember.
-
superdjango.shortcuts.library.
parse_string
(string, context)[source]¶ Parse a string as a Django template.
- Parameters
string (str) – The name of the template.
context (dict) – Context variables.
- Return type
str
-
superdjango.shortcuts.library.
parse_template
(template, context)[source]¶ Ad hoc means of parsing a template using Django’s built-in loader.
- Parameters
template (str || unicode) – The name of the template.
context (dict) – Context variables.
- Return type
str
-
superdjango.shortcuts.library.
static_file_exists
(path, tokens=None)[source]¶ Determine whether a static file exists.
- Parameters
path (str) – The path to be checked.
tokens (dict) – If given, format will be used to replace the tokens in the path.
- Return type
bool
-
superdjango.shortcuts.library.
template_exists
(name)[source]¶ Indicates whether the given template exists.
- Parameters
name (str) – The name (path) of the template to load.
- Return type
bool
-
superdjango.shortcuts.library.
there_can_be_only_one
(cls, instance, field_name)[source]¶ Helper function that ensures a given boolean field is
True
for only one record in the database. It is intended for use withpre_save
signals.- Parameters
cls (class) – The class (sender) emitting the signal.
instance – The instance to be checked.
field_name (str | unicode) – The name of the field to be checked. Must be a
BooleanField
.
- Type
instance: object
- Raises
AttributeError
if thefield_name
does not exist on theinstance
.
Storage¶
Utilities and backends for file storage.
Component Reference: Storage
ajax¶
Storage backends for uploading files via AJAX.
See :py:class`superdjango.ajax.views.AjaxFileUploader`.
Some of the code in this package was adapted and modernized from django-ajax-uploader.
overwrite¶
-
class
superdjango.storage.backends.overwrite.
OverwriteStorage
(*args, **kwargs)[source]¶ Bases:
django.core.files.storage.FileSystemStorage
Upload a file, overwriting an existing file.
constants¶
-
superdjango.storage.constants.
ALLOWED_CHARACTERS
= ['.', '_', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']¶ The characters that are allowed in a sanitized file name.
receivers¶
-
superdjango.storage.receivers.
handle_file_removal_on_change
(sender, **kwargs)[source]¶ Remove the files associated with a model when they have changed on the instance.
from django.db.models.signals import pre_save from superdjango.storage.receivers import handle_file_removal_on_change from myapp.models import Document pre_save.connect( handle_file_removal_on_change, Document, dispatch_uid="myapp_document_handle_file_removal_on_change" )
-
superdjango.storage.receivers.
handle_file_removal_on_delete
(sender, **kwargs)[source]¶ Remove any files associated with a model when an instance is deleted.
from django.db.models.signals import post_delete from superdjango.storage.receivers import handle_file_removal_on_delete from myapp.models import Document post_delete.connect( handle_file_removal_on_delete, Document, dispatch_uid="myapp_document_handle_file_removal_on_delete" )
signals¶
utils¶
-
superdjango.storage.utils.
generate_thumbnail
(path, height=200, prefix=None, suffix='thumbnail', width=200)[source]¶ Generate a thumbnail for the given image file.
- Parameters
path (str) – The path to the image file.
height (int) – The height of the thumbnail image.
prefix (str) – The prefix of the new thumbnail file. The width and height will be added to the prefix in the form of
prefix-WxH-file.extension
.suffix (str) – The suffix of the new thumbnail file. The width and height will be added to the suffix in the form of
file-suffix-WxH.extension
.width (int) – The width of the thumbnail image.
- Return type
str
- Returns
The path of the thumbnail file relative to
MEDIA_ROOT
.
Note
Either the prefix or suffix is used in the new file name, but not both.
-
superdjango.storage.utils.
get_unique_file_name
(file_name)[source]¶ Given a file name to be uploaded, get a unique name if the file already exists.
- Parameters
file_name (str) – The name of the file to be checked.
- Return type
str
-
superdjango.storage.utils.
get_upload_to
(instance, filename)[source]¶ Get the path to upload a content file.
- Parameters
instance – The model instance.
filename (str) – The name of the file.
- Return type
str
Important
The model instance must implement a
get_upload_to()
method.This allows the actual work of acquiring the upload path to be performed on the model where the file is defined.
from superdjango.storage import import get_upload_to, remove_non_ascii class Document(models.Model): file = models.FileField( _("file"), help_text=_("Select the file to upload."), upload_to=get_upload_to ) def get_upload_to(self, filename): file_name = self.file.field.storage.get_valid_name(filename) file_name = remove_non_ascii(file_name) directory_name = "documents" path = os.path.join(directory_name, file_name) return path
Utilities¶
General utilities not necessarily related to Django but nevertheless use for general operation.
Component Reference: Utilities
constants¶
-
superdjango.utils.constants.
BOOLEAN_VALUES
= (0, False, 'f', 'FALSE', 'False', 'false', 'N', 'n', 'NO', 'No', 'no', 1, True, 't', 'TRUE', 'True', 'true', 'Y', 'y', 'YES', 'Yes', 'yes')¶ A collection of values that should be identified as boolean.
-
superdjango.utils.constants.
FALSE_VALUES
= (0, False, 'f', 'FALSE', 'False', 'false', 'N', 'n', 'NO', 'No', 'no')¶ A collection of values that should evaluate to
False
.
-
superdjango.utils.constants.
TRUE_VALUES
= (1, True, 't', 'TRUE', 'True', 'true', 'Y', 'y', 'YES', 'Yes', 'yes')¶ A collection of values that should evaluate to
True
.
library¶
-
class
superdjango.utils.library.
File
(path)[source]¶ Bases:
object
A simple helper class for working with file names.
For more robust handling of paths, see pathlib.
-
property
exists
¶ Indicates the file exists.
- Return type
bool
-
property
-
superdjango.utils.library.
append_file
(path, content)[source]¶ Append to a file.
- Parameters
path (str) – The path to the file.
content (str) – The content to be appended the file.
from superdjango.utils import append_file append_file("path/to/readme.txt", "This is a test.")
-
superdjango.utils.library.
average
(values)[source]¶ Calculate the average of a given number of values.
- Parameters
values (list | tuple) – The values to be averaged.
- Return type
float
Ever get tired of creating a try/except for zero division? I do.
from superdjango.utils import average values = [1, 2, 3, 4, 5] print(average(values))
-
superdjango.utils.library.
base_convert
(number, from_digits='0123456789', to_digits='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz')[source]¶ Convert a number between two bases of arbitrary digits.
- Parameters
number (int) – The number to be converted.
from_digits (str) – The digits to use as the source of the conversion.
number
is included in these digits.to_digits (str) – The digits to which the number will be converted.
- Return type
str
-
superdjango.utils.library.
camelcase_to_underscore
(string)[source]¶ Convert a given string from
CamelCase
tocamel_case
.- Parameters
string (str) – The string to be converted.
- Return type
str
-
superdjango.utils.library.
copy_file
(from_path, to_path, make_directories=False)[source]¶ Copy a file from one location to another.
- Parameters
from_path (str || unicode) – The source path.
to_path (str || unicode) – The destination path.
make_directories (bool) – Create directories as needed along the
to_path
.
- Return type
tuple(bool, str)
- Returns
Success or failure and a message if failure.
from superdjango.utils import copy_file copy_file("readme-template.txt", "path/to/project/readme.txt")
-
superdjango.utils.library.
copy_tree
(from_path, to_path)[source]¶ Recursively copy a source directory to a given destination.
- Parameters
from_path (str) – The source directory.
to_path (str) – The destination directory. This must already exist.
- Return type
bool
- Returns
True
if successful.
Note
Errors are logged using the Python log.
from superdjango.utils import copy_tree success = copy_tree("from/path", "to/path") print(success)
-
superdjango.utils.library.
indent
(text, amount=4)[source]¶ Indent a string.
- Parameters
text (str) – The text to be indented.
amount (int) – The number of spaces to use for indentation.
- Return type
str
from superdjango.utils import indent text = "This text will be indented." print(indent(text))
-
superdjango.utils.library.
is_bool
(value, test_values=0, False, 'f', 'FALSE', 'False', 'false', 'N', 'n', 'NO', 'No', 'no', 1, True, 't', 'TRUE', 'True', 'true', 'Y', 'y', 'YES', 'Yes', 'yes')[source]¶ Determine if the given value is a boolean at run time.
- Parameters
value – The value to be checked.
test_values (list | tuple) – The possible values that could be True or False.
- Return type
bool
from superdjango.utils import is_bool print(is_bool("yes")) print(is_bool(True)) print(is_bool("No")) print(is_bool(False))
Note
By default, a liberal number of values are used to test. If you just want
True
orFalse
, simply pass(True, False)
astest_values
.
-
superdjango.utils.library.
is_integer
(value, cast=False)[source]¶ Indicates whether the given value is an integer. Saves a little typing.
- Parameters
value – The value to be checked.
cast (bool) – Indicates whether the value (when given as a string) should be cast to an integer.
- Return type
bool
from superdjango.utils import is_integer print(is_integer(17)) print(is_integer(17.5)) print(is_integer("17")) print(is_integer("17", cast=True))
-
superdjango.utils.library.
is_string
(value)[source]¶ Indicates whether the given value is a string. Saves a little typing.
- Parameters
value – The value to be checked.
- Return type
bool
from superdjango.utils import is_string print(is_string("testing")) print(is_string("17")) print(is_string(17))
-
superdjango.utils.library.
percentage
(portion, total)[source]¶ Calculate the percentage that a portion makes up of a total.
- Parameters
portion (float | int) – The portion of the total to be calculated as a percentage.
total (float | int) – The total amount.
- Return type
float
from superdjango.utils import percentage p = percentage(50, 100) print(p + "%")
-
superdjango.utils.library.
read_csv
(path, encoding='utf-8', first_row_field_names=False)[source]¶ Read the contents of a CSV file.
- Parameters
path (str) – The path to the file.
encoding (str) – The encoding of the file.
first_row_field_names (bool) – Indicates the first row contains the field names. In this case the returned rows will be a dictionary rather than a list.
- Return type
list[list] || list[dict]
menu,identifier,sort_order,text,url main,product,10,Product,/product/ main,solutions,20,Solutions,/solutions/ main,resources,30,Resources,/resources/ main,support,40,Support,https://support.example.com main,about,50,About,/about/ main,contact,60,Contact,/contact/
from superdjango.utils import read_csv rows = read_csv("path/to/menus.csv", first_row_fields_names=True) for r in rows: print("%s: %s" % (row['identifier'], row['url']
-
superdjango.utils.library.
read_file
(path)[source]¶ Read a file and return its contents.
- Parameters
path (str || unicode) – The path to the file.
- Return type
str
from superdjango.utils import read_file output = read_file("path/to/readme.txt") print(output)
-
superdjango.utils.library.
smart_cast
(value)[source]¶ Intelligently cast the given value to a Python data type.
- Parameters
value (str) – The value to be cast.
Strip HTML tags from a string.
- Parameters
html (str | unicode) – The string from which HTML tags should be stripped.
- Return type
str
from superdjango.utils import strip_html_tags html = "<p>This string contains <b>HTML</b> tags.</p>" print(strip_html_tags(html))
-
superdjango.utils.library.
to_bool
(value, false_values=0, False, 'f', 'FALSE', 'False', 'false', 'N', 'n', 'NO', 'No', 'no', true_values=1, True, 't', 'TRUE', 'True', 'true', 'Y', 'y', 'YES', 'Yes', 'yes')[source]¶ Convert the given value to it’s boolean equivalent.
- Parameters
value – The value to be converted.
false_values (list | tuple) – The possible values that could be False.
true_values (list | tuple) – The possible values that could be True.
- Return type
bool
- Raises
ValueError
if the value could not be converted.
from superdjango.utils import to_bool print(to_bool("yes")) print(to_bool(1)) print(to_bool("no")) print(to_bool(0))
-
superdjango.utils.library.
truncate
(string, continuation='...', limit=30)[source]¶ Get a truncated version of a string if if over the limit.
- Parameters
string (str || None) – The string to be truncated.
limit (int) – The maximum number of characters.
continuation (str || None) – The string to add to the truncated title.
- Return type
str
from superdjango.utils import truncate title = "This Title is Too Long to Be Displayed As Is" print(truncate(title))
-
superdjango.utils.library.
underscore_to_camelcase
(string)[source]¶ Convert a string with underscore separations to CamelCase.
- Parameters
string (str) – The string to be converted.
- Return type
str
-
superdjango.utils.library.
underscore_to_title_case
(string)[source]¶ Convert a string to title case.
- Parameters
string (str) – The string to be converted.
- Return type
str
-
superdjango.utils.library.
write_file
(path, content='', make_directories=False)[source]¶ Write a file.
- Parameters
path (str || unicode) – The path to the file.
content (str || unicode) – The content of the file. An empty string is effectively the same as a “touch”.
make_directories (bool) – Create directories as needed along the file path.
from superdjango.utils import write_file write_file("path/to/readme.txt", "This is a test.")
Views¶
High-level, class-based views that may be used in practically all of the common use cases for Web application development.
Component Reference: Views
access¶
-
class
superdjango.views.access.
AccessMixin
[source]¶ Bases:
object
Provides attributes and methods for checking user authentication and permissions in a view.
-
check_login
(request, *args, **kwargs)[source]¶ Check that the user is authenticated if authentication is required. Also checks
staff_required
andsuperuser_required
.- Parameters
request – The current request object.
- Return type
bool
- Returns
True
is the user can access the current view.
-
check_membership
(request, *args, **kwargs)[source]¶ Check group membership to see if the user can access the view.
- Parameters
request – The current request object.
- Return type
bool
- Returns
True
is the user can access the current view.
-
check_other
(request, *args, **kwargs)[source]¶ Customize this method as needed to perform any additional access checks.
- Return type
bool
This example requires that a user has logged in within the last 90 days.
# views.py from django.conf import settings from django.contrib.auth.views import logout_then_login from datetime import timedelta from django.utils.timezone import now class MyView(AccessMixin): def check_other(self, request, *args, **kwargs): ninety_days = 60 * 60 * 24 * 90 current_dt = now() delta = timedelta(seconds=ninety_days) if current_dt > (request.user.last_login + delta): return False return True def dispatch_other(reason, request, redirect_url=None): return logout_then_login(request, redirect_url or settings.LOGIN_URL)
The
AccessMixin
need not be restricted to authentication and authorization. This example requires that the user be anonymous (not logged in) and redirects to another location. Note that all other checks (except SSL) must beFalse
orNone
.# views.py class MyPublicView(AccessMixin): def check_other(self, request, *args, **kwargs): if request.user.is_authenticated: return False return True def dispatch_other(reason, request, redirect_url=None): return reverse("accounts_profile")
-
check_permission
(request, *args, **kwargs)[source]¶ Check that the current user has permission to access the view.
- Parameters
request – The current request object.
- Return type
bool
- Returns
True
is the user can access the current view.
-
check_ssl
(request, *args, **kwargs)[source]¶ Check that the connection is secure as requested.
- Parameters
request – The current request object.
- Return type
bool
- Returns
True
is the check passes. This means that the connection is secure whenssl_required
isTrue
or that no check (one way or the other) is necessary becausessl_required
isFalse
.
Note
ssl_required
is ignored whenDEBUG
isTrue
.
-
dispatch
(request, *args, **kwargs)[source]¶ Dispatch the request, checking for authentication and permission as needed.
Access is checked in the following order:
Check for SSL.
Check for an authenticated user.
Check for group membership.
Check for specific permissions.
Call
check_other()
. Seedispatch_other()
.
-
dispatch_access_denied
(request, message=None, redirect_url=None)[source]¶ Handle authentication or permission issues during dispatch.
- Parameters
request – The current request object.
message (str) – A reason for the permission failure.
redirect_url (str) – The URL to which the user should be directed.
-
dispatch_insecure
(request, message=None)[source]¶ Dispatch insecure requests.
- Parameters
request – The current request object.
message (str) – A reason for the permission failure.
-
dispatch_other
(request, message=None, redirect_url=None)[source]¶ Responds to failed
check_other()
. Override this method to provide your own handling.- Parameters
request – The current request object.
message (str) – A reason for the permission failure.
redirect_url (str) – The URL to which the user should be directed.
Note
By default, this method simply calls
dispatch_access_denied()
.
-
group_required
= None¶ The group, if any, that a user must belong to in order to access the current view. Multiple groups may be specified as a list.
-
logging_enabled
= False¶ Indicates access logging is enabled.
-
login_required
= False¶ Indicates that the user must be logged in to access the current view.
-
permission_required
= None¶ The permission name required to access the current view in the form of
app_label.permission_name
. Multiple permissions may be specified as a list.
-
raise_access_exception
= False¶ Indicates whether exceptions should be raised during dispatch or mitigated, if possible.
-
redirect_to_login
(path)[source]¶ Redirect to the login view using the given path as the next URL.
- Parameters
path (str) – The next URL after logging in.
-
ssl_required
= False¶ Indicates whether child views must be served via a secure connection.
-
staff_required
= False¶ Indicates
is_staff
must be set toTrue
on the user’s account.
-
superuser_required
= False¶ Indicates
is_superuser
must be set toTrue
on the user’s account.
-
-
class
superdjango.views.access.
LoginRequiredMixin
[source]¶ Bases:
superdjango.views.access.AccessMixin
Extend the standard
AccessMixin
to setlogin_required = True
.
ajax¶
Why no AJAXMixin?
An AJAX mixin similar to Braces’ AjaxResponseMixin simply allows a view for “fork” behavior based on
request.is_ajax()
. We feel a better practice is to create a view that specifically handles AJAX requests because
this is much more obvious, easier to test, and reduces the code complexity of the view.
-
class
superdjango.views.ajax.
AjaxFileUploader
(backend=None, **kwargs)[source]¶ Bases:
object
This pseudo-view class provides support for uploading files via AJAX.
Setup
The JavaScript files for AJAX upload are located in the assets app, so make sure you have this in your
settings.py
file:INSTALL_APPS = [ # ... "superdjango.assets.apps.DefaultConfig", # ... ]
Usage
Create a view for handling the upload. In the example below, the ajax_uploader view is initialized (without any options) at the bottom of the file. The
upload_form()
view is used to present an AJAX-enabled upload form. You may wish to integrate this into your own form view and template instead.from django.middleware.csrf import get_token from django.shortcuts import render_to_response from django.template import RequestContext from superdjango.ajax.uploads.views import AjaxFileUploader def upload_form(request): csrf_token = get_token(request) return render_to_response( 'upload_form.html', {'csrf_token': csrf_token}, context_instance=RequestContext(request) ) ajax_uploader = AjaxFileUploader()
Add the views to your main
urls.py
file:from superdjango.ajax import views as ajax_upload_views urlpatterns = [ # ... path(r'ajax/upload/start/)', ajax_upload_views.upload_form, name="upload_form"), path(r'ajax/upload/', ajax_upload_views.import_uploader, name="ajax_upload"), # ... ]
Create a template or add to the template where the upload should occur:
{% load i18n %} {% load static %} <!doctype html> <head> <script src="{% static "bundled/fileuploader/js/fileuploader.js" %}" ></script> <link href="{% static "bundled/fileuploader/css/fileuploader.css" %}" rel="stylesheet" /> <script> $(function(){ var uploader = new qq.FileUploader({ action: "{% url ajax_upload %}", element: $('#file-uploader')[0], multiple: true, onComplete: function(id, fileName, responseJSON) { if (responseJSON.success) { alert("success!"); } else { alert("upload failed!"); } }, onAllComplete: function(uploads) { // uploads is an array of maps // the maps look like this: {file: FileObject, response: JSONServerResponse} alert("All complete!"); }, params: { 'csrf_token': '{{ csrf_token }}', 'csrf_name': 'csrfmiddlewaretoken', 'csrf_xname': 'X-CSRFToken', }, }); }); </script> </head> <body> <div id="file-uploader"> <noscript> <p>{% trans "Please enable JavaScript to use the file uploader." %}</p> </noscript> </div> </body> </html>
-
class
superdjango.views.ajax.
JSONMixin
[source]¶ Bases:
object
Handle JSON requests/responses.
from superdjango.views import GenericView, JSONMixin class MyAjaxView(JSONMixin, GenericView): def post(self, request, *args, **kwargs): # process the request that produces a dict or queryset or model instance. data = self.get_some_data() return self.get_json_response(data)
-
ajax_required
= False¶ Indicates requests must be made via AJAX. Defaults to
False
in development.
-
content_type
= 'application/json'¶ The expected content type of the request or response.
-
decoder_class
= None¶ Optional class used to decode the request. It takes the current request instance as the only parameter and must implement a load method which returns a
dict
.
-
dispatch
(request, *args, **kwargs)[source]¶ Set
request_json
and validate the request before continuing with the dispatch.
-
dispatch_bad_request
(error=None, **kwargs)[source]¶ Handle a bad request.
- Parameters
error (dict) – A dictionary describing the error in the form of
{'error': "Description."}
. Defaults to{'error': "Bad request."}
Keyword arguments are passed to
json.dumps()
.
-
encoder_class
¶ alias of
django.core.serializers.json.DjangoJSONEncoder
-
get_json_response
(data, status=200, **kwargs)[source]¶ Get the JSON response.
- Parameters
data (dict | list | tuple | django.db.models.QuerySet) – The data to be serialized. If this is a dictionary, simple serialization is used using the
encoder_class
attribute. If a QuerySet is given, Django’s built-in serializer is used.status (int) – The HTTP status code.
Additional keyword arguments are passed to
json.dumps()
or Django’s serializer.- Return type
HttpResponse
Warning
If
data
is not provided as adict
,list
, ortuple
it is assumed to be a QuerySet. This will produce unexpected results if you fail to provide the supported data type.
-
json_required
= False¶ Indicates that requests must be made using JSON.
-
base¶
-
class
superdjango.views.base.
BaseView
(**kwargs)[source]¶ Bases:
django.views.generic.base.View
A mixin for establishing core functionality for all views.
-
active_page
= None¶ The name of the active page that may be used to identify the current view within a menu.
-
active_subpage
= None¶ The name of the active subpage that may be used to identify the current view within a submenu.
-
base_template_name
= 'base.html'¶ The base template to extend.
-
css
= None¶ A list of CSS markup elements that maybe added to the output. See
get_css()
.
-
dispatch_not_found
(message=None)[source]¶ Dispatch a 404 (page not found) error. By default, this just raises an
Http404
.- Parameters
message – The 404 message.
-
get_base_template
()[source]¶ Get the name of the base template to use for rendering the view.
- Return type
str
-
get_context_data
(**kwargs)[source]¶ Uses keyword arguments as the base context and adds the current view instance as
view
.- Return type
dict
The following variables are added to the context:
active_page
: The identifier for the active menu item.active_subpage
: The identifier for the active sub-menu item.base_template
: The template to extend, i.e.{% extends base_template %}
.subtitle
: The subtitle of the page.title
: The title of the page.view
: The current view instance.view_css
: A Style instance.view_js
: A JavaScript instance.
-
get_template_names
()[source]¶ Get the name of the template used to render the response.
- Return type
list[str]
-
js
= None¶ A list of JavaScript markup elements that maybe added to the output. See
get_js()
.
-
raise_exception
= False¶ Indicates whether exceptions should be raised during processing or mitigated, if possible.
-
render_to_response
(context)[source]¶ Render the current context.
- Parameters
context – The context variables to use for rendering.
- Return type
TemplateResponse
-
subtitle
= None¶ The subtitle of the page.
-
template_name
= None¶ The name of the template to use for rendering the view.
-
title
= None¶ The title of the page.
-
-
superdjango.views.base.
GenericView
¶ alias of
django.views.generic.base.View
breadcrumbs¶
Bases:
object
A view mixin which incorporates breadcrumbs into the template context.
Get the breadcrumbs for the view.
- Return type
Add
breadcrumbs
to the context.
crud¶
-
class
superdjango.views.crud.
CreateView
(**kwargs)[source]¶ Bases:
superdjango.views.crud.ModelView
Present, validate, and submit a form for a new model record (instance).
Note
Because
ModelView`
extendsFormMixin
, this class does not need to implementget()
,get_form()
,form_invalid()
, orpost()
.See also
ModelView.get_success_url()
.
-
class
superdjango.views.crud.
DeleteView
(**kwargs)[source]¶ Bases:
superdjango.views.crud.ModelView
Delete and existing model record (instance).
-
class
superdjango.views.crud.
DetailView
(**kwargs)[source]¶ Bases:
superdjango.views.crud.ModelView
Display detail for a model record (instance).
-
class
superdjango.views.crud.
ListView
(**kwargs)[source]¶ Bases:
superdjango.views.crud.ModelView
List model records.
-
allow_empty
= True¶ Indicates whether an empty queryset is allowed. When
False
an empty queryset will raise anHttp404
.
-
empty_message
= None¶ The message to display when there are no results.
-
get
(request, *args, **kwargs)[source]¶ Get the queryset and optionally apply pagination.
The context includes
no_results_message
whenallow_empty
isTrue
and no results are found.is_paginated
is also included and is eitherTrue
orFalse
.If pagination is enabled, additional variables are also added to the context:
current_page
: The same aspage_object
.page_keyword
: The GET keyword used to indicate the current page number.page_obj
: The current page object fromget_paginated_queryset()
.pagination_style
: The preferred output of pagination links.paginator
: The paginator instance fromget_paginator()
.
-
get_page_keyword
()[source]¶ Get the keyword used to identify the page number in GET.
- Return type
str
-
get_paginated_queryset
(queryset, limit)[source]¶ Paginate the given queryset.
- Parameters
queryset (django.db.Queryset) – The query set to be paginated.
limit (int) – The number of objects per page.
- Return type
Page
-
limit
= None¶ The total records to be displayed on a page. Setting this value will invoke pagination.
-
page_keyword
= 'page'¶ The GET key used to indicate the pagination page number. Defaults to
page
.
-
pagination_style
= 'previous-next'¶ The style for navigation through paginated results,
numbers
orprevious-next
.
-
-
class
superdjango.views.crud.
ModelView
(**kwargs)[source]¶ Bases:
superdjango.views.forms.FormMixin
,superdjango.views.base.BaseView
Base class for model interactions.
To avoid the excessive use of mixins, an engineering compromise was struck when developing the
ModelView
:The view extends the base view which includes a number of commonly useful features and context variables.
The view also extends
FormMixin
, which doesn’t make sense for detail and list views, but provides the basis for sensible defaults with create and update views.The delete view may be customized to include a form if one is desired. For example, to add a checkbox for an additional confirmation step.
Other than
get_object_list()
and use ofget_queryset()
,ModelView
does not implement list logic.ListView
provides this instead.No authentication or authorization logic is provided by default. It is up to the developer to utilize
superdjango.views.access
or their own custom logic if these features are desired.
-
context_object_name
= None¶ The name of the model object or objects when used in a template.
-
field_names
= None¶ A list of field names to be included in the view. For form views, these are the names included in the form. For detail and list views, these may be used to display record data.
-
classmethod
get_app_label
()[source]¶ Get the app label (name) for the model represented by the view.
- Return type
str
-
get_cancel_url
()[source]¶ Return the value of the class attribute, if defined. Otherwise attempt to return the list view for the current model.
- Return type
str | None
-
get_context_data
(**kwargs)[source]¶ Get context used to render the response.
The following variables are added to the context:
verbose_name
: The verbose name of the model.verbose_name_plural
: The plural name of the model.
For single-object views, the
object
variable is also added along with a specific name ifcontext_object_name
is defined.For multi-object views, the
object_list
variable is added along with a specific name ifcontext_object_name
is defined.
-
get_context_object_name
()[source]¶ Get the name of the model (or models) used in templates.
- Return type
str | None
-
get_field_names
()[source]¶ Get the field names to be included in the model form.
- Return type
list[str]
Tip
If the
field_names
class attribute is not defined, all of the model’s fields are included, which is probably not what you want.
-
get_form_class
()[source]¶ Get the form class to use for instantiating a model form. If
form_class
is not defined, thedjango.forms.models.modelform_factory()
is used in conjunction withget_field_names()
.- Raise
AttributeError
-
classmethod
get_lookup_field
()[source]¶ Get the name of the field used to uniquely identify a model instance.
- Return type
str
- Raises
IMustBeMissingSomething
-
classmethod
get_lookup_key
()[source]¶ Get the key used in GET to uniquely identify a model instance.
- Return type
str
-
classmethod
get_model
()[source]¶ Get the model class used by the view.
- Raise
IMustBeMissingSomething
Note
This saves checking for the model in the various class methods rather than accessing
cls.model
and handling the exception every time the model is referenced.
-
classmethod
get_model_name
()[source]¶ Get the model name in lower case.
- Return type
str
- Raise
IMustBeMissingSomething
- Raises
See
get_model()
.
-
get_object
()[source]¶ Get the object (model instance) that may be used in
CreateView
,DetailView
, andDeleteView
.
-
get_object_list
()[source]¶ Get the objects to be displayed by list views.
- Return type
django.db.models.QuerySet
-
get_queryset
()[source]¶ Get the queryset used by the view. This will either be a list or individual instance.
- Return type
django.db.models.QuerySet
-
get_success_url
()[source]¶ Return the value of the class attribute, if defined. Otherwise attempt to return the list view for the current model. Alternatively, the absolute URL will be returned if the model defines
get_absolute_url()
.- Raise
IMustBeMissingSomething
-
get_template_name_suffix
()[source]¶ Get the suffix for the current view template.
- Return type
str
Tip
Extending classes should define the
template_name_suffix
. The suffix should include an underscore for separation. For example, the suffix for a view for creating a new record would be_add
.The default behavior here is to return an empty string if
template_name_suffix
is not defined.
-
get_template_names
()[source]¶ Get the template names that may be used for rendering the response.
- Return type
list[str]
The possible names are generated like so:
If the child class defines a
template_name
, this is always returned as the first element of the list.This method first defines templates that may be defined by the local project in the form of
{app_label}/{model_name_lower}{template_name_suffix}.html
.
-
lookup_field
= 'pk'¶ The field used to uniquely identify the model.
-
lookup_key
= None¶ The key in GET used to uniquely identify the model. Defaults to the
lookup_field
.
-
model
= None¶ The model (class) to which the view pertains. Required.
-
object
= None¶ The record (instance) of a model for create, detail, delete, and update views. This is not used by list views.
-
object_list
= None¶ The record instances of a model for list views.
A list of foreign key or many to many fields that should be called using Django’s prefetch_related.
-
queryset
= None¶ The queryset used to acquire the object or object list. See
get_queryset()
.
A list of foreign key fields that should be called using Django’s select_related.
-
template_name_suffix
= None¶ The suffix added to the end of template names when automatically generated. This should be overridden by child classes.
-
class
superdjango.views.crud.
UpdateView
(**kwargs)[source]¶ Bases:
superdjango.views.crud.ModelView
Update and existing model record (instance).
Note
Because
ModelView`
extendsFormMixin
, this class does not need to implementget_form()
orform_invalid()
.get()
andpost()
must be implemented so that the current model instance is bound to the form.See also
ModelView.get_success_url()
.
forms¶
-
class
superdjango.views.forms.
CSRFExemptMixin
[source]¶ Bases:
object
Provides CSRF exemption for a view.
Note
When used, this mixin should be the left-most class of the view.
-
class
superdjango.views.forms.
ConfirmView
(**kwargs)[source]¶ Bases:
superdjango.views.forms.FormMixin
,superdjango.views.base.BaseView
Provide a simple confirmation page before proceeding with another action.
Note that
form_valid()
andform_invalid()
are ignored, and that no form or form class is used.The template is used to provide the confirmation:
<form method="post"> {% csrf_token %} <p>{%trans "Are you sure you want to do this?" %}</p> {% html "form_submit" %} </form>
In order for the view to do something, the
submit()
method must be overridden:from superdjango.ui.views import ConfirmView class MyConfirmView(ConfirmView): pattern_name = "my_confirm_view" pattern_value = 'my/confirmation/' def submit(self, request): # Do something after the form has been submitted.
Use the
confirmed_keyword
if you need to post data to the confirmation view prior to actual confirmation.from superdjango.ui.views import ConfirmView class MyConfirmView(ConfirmView): confirmed_keyword = "confirmed" pattern_name = "my_confirm_view" pattern_value = 'my/confirmation/' def submit(self, request): # Do something after the form has been submitted.
The template would also need to include the confirmation keyword:
<form method="post"> {% csrf_token %} <input type="hidden" name="{{ confirmed_keyword }}" value="1"> <p>{%trans "Are you sure you want to do this?" %}</p> {% html "form_submit" %} </form>
-
confirmed_keyword
= 'confirmed'¶ The keyword submitted via POST that may used to confirm the next action.
-
-
class
superdjango.views.forms.
FormMixin
[source]¶ Bases:
superdjango.views.messages.MessageMixin
Provides form-related methods and attributes.
-
cancel_text
= None¶ The text to display as part of the cancel URL.
-
cancel_url
= None¶ The URL to which the user should be sent when canceling the confirmation.
-
error_message
= None¶ The message to be displayed for an invalid (failed) form submission.
-
form_class
= None¶ The class to use for rendering forms.
-
get_context_data
(**kwargs)[source]¶ Add form-specific values to the context.
cancel_text
cancel_url
form
submit_text
-
get_error_message
()[source]¶ Get the error message for an invalid form submission.
- Return type
str | None
-
get_form
(data=None, files=None, **kwargs)[source]¶ Get the form instance.
- Parameters
data (QueryDict) – The form data.
files (QueryDict) – Files data.
- Returns
The instantiated form instance.
Any additional keyword arguments are passed directly to the form.
-
get_success_message
()[source]¶ Get the message to be displayed after a successful form submision.
- Return type
str | None
-
get_success_url
()[source]¶ Get the URL to which the user should be sent on successful form submit.
- Return type
str
-
submit_text
= None¶ The text to display for the submit button.
-
success_message
= None¶ The message to be displayed after a valid (successful) form submission.
-
success_url
= None¶ The URL to which a user is sent after a successful (valid) form submission.
-
-
class
superdjango.views.forms.
FormView
(**kwargs)[source]¶ Bases:
superdjango.views.forms.FormMixin
,superdjango.views.base.BaseView
Display and handle form submission.
images¶
-
class
superdjango.views.images.
ImageView
(**kwargs)[source]¶ Bases:
superdjango.views.templates.TemplateView
Generic view for displaying images in full-screen.
Configuration
Add
superdjango.assets.apps.DefaultConfig
toINSTALLED_APPS
.Usage
Create a view that extends
ImageView
:# views.py from superdjango.ui.views import ImageView class MyImage(ImageView): pattern_name = "display_image" pattern_value = "images/"
Tip
For more control over the template, set the
template_name
on your view. See the providedimage_view.html
for an example.You may call your view in a template, passing the following parameters via GET:
i
(required): The URL of the image.t
(optional): A title for the image.z
(optional): Set to1
to enable zoom. Default is0
(disabled).
For example, assuming you’ve defined a model with an
image
field:# template.html <img src="{{ object.image.url }}" class="thumbnail"> <p> <a href="{% url "display_image" %}?i={{ object.image.url }}&t={{ object.title|urlencode }}" target="_blank"> {% trans "Full Screen" %} </a> </p>
The provided
image_view.html
template extendsSUPERDJANAGO_BASE_TEMPLATE_NAME
and expects the following template code to exist in that template.{% if view_css %} {% for html in view_css %} {{ html }} {% endfor %} {% endif %} {% if view_js %} {% for html in view_js %} {{ html }} {% endfor %} {% endif %}
messages¶
Messages provide feedback to users as things happen within an application. The MessageMixin
enables this feedback
for a view.
-
class
superdjango.views.messages.
MessageAPIBinder
[source]¶ Bases:
object
Binds the
MessageAPIWrapper
to a view.
-
class
superdjango.views.messages.
MessageAPIWrapper
(request)[source]¶ Bases:
object
Wraps the
django.contrib.messages.api
module to capture the current request instance for function calls.
-
class
superdjango.views.messages.
MessageMixin
[source]¶ Bases:
object
Add a
messages`
attribute on the view instance that wrapsdjango.contrib.messages
.Many HTML/CSS frameworks such as Twitter Bootstrap or UIKit have styles for
info
,success
, andwarning
, but usedanger
for the equivalent oferror
. You can address this by adding the following to yoursettings.py
file:from django.contrib import messages # Map "error" to "danger" for Bootstrap/UIKit alerts. from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.ERROR: "danger", }
See https://docs.djangoproject.com/en/stable/ref/contrib/messages/
redirects¶
-
class
superdjango.views.redirects.
CallbackRedirectView
(**kwargs)[source]¶ Bases:
django.views.generic.base.RedirectView
Allows the specification of a redirect callback when the view is created.
-
redirect_callback
= None¶ A callable that is used to issue the redirect. It should accept a request argument and return an
HTTPResponseRedirect
.
-
-
class
superdjango.views.redirects.
CountRedirectView
(**kwargs)[source]¶ Bases:
superdjango.views.messages.MessageMixin
,django.views.generic.base.RedirectView
Logs a “hit” before redirecting.
-
counter_callback
= None¶ A callable that may be used to the activity. If defined, the callback is passed the request instance and redirect URL, as in
callback(request, url)
.
-
-
class
superdjango.views.redirects.
DelayedRedirectView
(**kwargs)[source]¶ Bases:
superdjango.views.messages.MessageMixin
,superdjango.views.templates.TemplateView
Redirect the user after a delay.
-
countdown_enabled
= True¶ Indicates whether a countdown should be displayed.
-
delayed_seconds
= 5¶ The number of seconds to wait before issuing the redirect.
-
get_context_data
(**kwargs)[source]¶ Add delayed redirect variables to the context.
countdown_enabled
delayed_seconds
redirect_url
-
redirect_url
= None¶ The URL to which the user should be redirected.
-
template_name
= 'superdjango/views/delayed_redirect.html'¶ The default template to use for the redirect page.
-
-
class
superdjango.views.redirects.
RedirectView
(**kwargs)[source]¶ Bases:
superdjango.views.messages.MessageMixin
,django.views.generic.base.RedirectView
A redirect view which incorporates message functionality.
templates¶
-
class
superdjango.views.templates.
TemplateView
(**kwargs)[source]¶ Bases:
superdjango.views.base.BaseView
Render and display a template.
Tip
template_name
orget_template_names()
must be defined.
viewsets¶
-
class
superdjango.views.viewsets.
ModelViewSet
(app_name=None, namespace=None)[source]¶ Bases:
superdjango.views.viewsets.ViewSet
Extends
ViewSet
to add support for models.BaseView Name
Unless the
get_pattern_name()
method is defined on the view, the name will be automatically determined based on the name of the model plus a suffix for the purpose of the view class:_create
_delete
_detail
_list
_update
The name of the view (used to reverse the URL) is established in the following manner:
Use the
pattern_name
property if it has been set on the view class.Use the result of
get_pattern_name()
if the method is defined on the view class.If the view is an extension of any of the model views, the name will be automatically set based on the name of the model plus the purpose of the view class:
_create
,_delete
,_detail
,_list
, and_update
.If none of the other methods have produced a result, the name of the view class will be used. This is rarely ideal, but does provide a default and prevents throwing an error.
Pattern Value
Unless the
get_pattern_value()
method is defined, the base pattern will be automatically determined based on the purpose of the view class:create
delete
detail
update
List views are assumed to be the index of the app’s URLs. Views that require an identifier will use the
lookup_field
on the view class.Example
# views.py from superdjango.views.models import CreateView, DeleteView, DetailView, ListView, UpdateView from superdjango.views.viewsets import ModelViewSet from .models import Task class CreateTask(CreateView): model = Task # ... class DeleteTask(DeleteView): model = Task # ... class ListTasks(ListView) model = Task # ... class TaskDetail(DetailView): model = Task # ... class UpdateTask(UpdateView): model = Task # ... class TaskViewSet(ViewSet): views = [ CreateTask, DeleteTask, ListTasks, TaskDetail, UpdateTask, ]
# urls.py from views import TaskViewSet urlpatterns = TaskViewSet().get_urls()
-
classmethod
get_pattern_name
(view_class)[source]¶ Get the name of a view based on the implemented model view.
- Parameters
view_class (class) – The class-based view.
- Return type
str
- Raise
NoViewForYou
-
class
superdjango.views.viewsets.
ViewSet
(app_name=None, namespace=None)[source]¶ Bases:
object
A generic viewset, the main purpose of which is to collect views together to consistently generate their URLs.
-
__init__
(app_name=None, namespace=None)[source]¶ Initialize a generic view set.
- Parameters
app_name (str) – The app name.
namespace (str) – The namespace in which the app will operate.
-
classmethod
get_pattern_name
(view_class)[source]¶ Get the name of a view.
- Parameters
view_class (class) – The class-based view.
- Return type
str
- Raise
ImproperlyConfigured
Note
The view may override the default behavior by implementing a
pattern_name
property or theget_pattern_name()
method. This method must return astr
.
-
classmethod
get_pattern_regex
(view_class)[source]¶ Get the regular expression of a view.
- Parameters
view_class (class) – The class-based view.
- Return type
str | None
Note
This method does not raise an improperly configured, allowing the other methods to fall back to
get_pattern_value()
.
-
classmethod
get_pattern_value
(view_class)[source]¶ Get the value (path) of a view.
- Parameters
view_class (class) – The class-based view.
- Return type
str
- Raise
ImproperlyConfigured
-
get_url
(view_class, prefix=None)[source]¶ Get the url of a view.
- Parameters
view_class (class) – The class-based view.
prefix – A prefix added to the regex. Note that the URL will fail to resolve if the
^
appears in the regex for the view.
- Return type
URLPattern
Note
The view may override the default behavior by implementing a
get_url()
method. This method must return an instance ofURLPattern
usingre_path()
orpath()
.
-