Packages¶
Below are auto-generated docs mostly covering each of the packages contained
within Mezzanine that are added to settings.INSTALLED_APPS.
mezzanine.boot¶
An app that is forced to the top of the list in INSTALLED_APPS
for the purpose of hooking into Django’s class_prepared signal
and adding custom fields as defined by the EXTRA_MODEL_FIELDS
setting. Also patches django.contrib.admin.site to use
LazyAdminSite that defers certains register/unregister calls
until admin.autodiscover to avoid some timing issues around
custom fields not being available when custom admin classes are
registered.
-
mezzanine.boot.add_extra_model_fields(sender, **kwargs)¶ Injects custom fields onto the given sender model as defined by the
EXTRA_MODEL_FIELDSsetting.
-
mezzanine.boot.autodiscover(*args, **kwargs)¶ Replaces django’s original autodiscover to add a call to LazyAdminSite’s lazy_registration.
mezzanine.core¶
Provides abstract models and admin features used throughout the various Mezzanine apps.
mezzanine.core.models¶
-
class
mezzanine.core.models.Displayable(*args, **kwargs)¶ Abstract model that provides features of a visible page on the website such as publishing fields. Basis of Mezzanine pages, blog posts, and Cartridge products.
-
get_absolute_url()¶ Raise an error if called on a subclass without
get_absolute_urldefined, to ensure all search results contains a URL.
-
get_next_by_publish_date(**kwargs)¶ Retrieves next object by publish date.
-
get_previous_by_publish_date(**kwargs)¶ Retrieves previous object by publish date.
-
publish_date_since()¶ Returns the time since
publish_date.
-
save(*args, **kwargs)¶ Set default for
publish_date. We can’t useauto_now_addon the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard.
-
-
class
mezzanine.core.models.MetaData(*args, **kwargs)¶ Abstract model that provides meta data for content.
-
description_from_content()¶ Returns the first block or sentence of the first content-like field.
-
meta_title()¶ Accessor for the optional
_meta_titlefield, which returns the string version of the instance if not provided.
-
save(*args, **kwargs)¶ Set the description field on save.
-
-
class
mezzanine.core.models.Orderable(*args, **kwargs)¶ Abstract model that provides a custom ordering integer field similar to using Meta’s
order_with_respect_to, since to date (Django 1.2) this doesn’t work withForeignKey("self"), or with Generic Relations. We may also want this feature for models that aren’t ordered with respect to a particular field.-
delete(*args, **kwargs)¶ Update the ordering values for siblings.
-
get_next_by_order(**kwargs)¶ Retrieves next object by order.
-
get_previous_by_order(**kwargs)¶ Retrieves previous object by order.
-
save(*args, **kwargs)¶ Set the initial ordering value.
-
with_respect_to()¶ Returns a dict to use as a filter for ordering operations containing the original
Meta.order_with_respect_tovalue if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation’sct_fieldandfk_fieldattributes.
-
-
class
mezzanine.core.models.OrderableBase¶ Checks for
order_with_respect_toon the model’s innerMetaclass and if found, copies it to a custom attribute and deletes it since it will cause errors when used withForeignKey("self"). Also creates theorderingattribute on theMetaclass if not yet provided.
-
class
mezzanine.core.models.Ownable(*args, **kwargs)¶ Abstract model that provides ownership of an object for a user.
-
is_editable(request)¶ Restrict in-line editing to the objects’s owner and superusers.
-
-
class
mezzanine.core.models.RichText(*args, **kwargs)¶ Provides a Rich Text field for managing general content and making it searchable.
-
class
mezzanine.core.models.SitePermission(*args, **kwargs)¶ Permission relationship between a user and a site that’s used instead of
User.is_staff, for admin and inline-editing access.
-
class
mezzanine.core.models.SiteRelated(*args, **kwargs)¶ Abstract model for all things site-related. Adds a foreignkey to Django’s
Sitemodel, and filters by site with all querysets. Seemezzanine.utils.sites.current_site_idfor implementation details.-
save(update_site=False, *args, **kwargs)¶ Set the site to the current site when the record is first created, or the
update_siteargument is explicitly set toTrue.
-
-
class
mezzanine.core.models.Slugged(*args, **kwargs)¶ Abstract model that handles auto-generating slugs. Each slugged object is also affiliated with a specific site object.
-
get_slug()¶ Allows subclasses to implement their own slug creation logic.
-
save(*args, **kwargs)¶ Create a unique slug by appending an index.
-
-
class
mezzanine.core.models.TimeStamped(*args, **kwargs)¶ Provides created and updated timestamps on models.
mezzanine.core.managers¶
-
class
mezzanine.core.managers.CurrentSiteManager(field_name=None, *args, **kwargs)¶ Extends Django’s site manager to first look up site by ID stored in the request, the session, then domain for the current request (accessible via threadlocals in
mezzanine.core.request), the environment variableMEZZANINE_SITE_ID(which can be used by management commands with the--sitearg, finally falling back tosettings.SITE_IDif none of those match a site.
-
class
mezzanine.core.managers.DisplayableManager(field_name=None, *args, **kwargs)¶ Manually combines
CurrentSiteManager,PublishedManagerandSearchableManagerfor theDisplayablemodel.
-
class
mezzanine.core.managers.PublishedManager¶ Provides filter for restricting items returned by status and publish date when the given user is not a staff member.
-
published(for_user=None)¶ For non-staff users, return items with a published status and whose publish and expiry dates fall before and after the current date when specified.
-
-
class
mezzanine.core.managers.SearchableManager(*args, **kwargs)¶ Manager providing a chainable queryset. Adapted from http://www.djangosnippets.org/snippets/562/ search method supports spanning across models that subclass the model being used to search.
-
contribute_to_class(model, name)¶ Django 1.5 explicitly prevents managers being accessed from abstract classes, which is behaviour the search API has relied on for years. Here we reinstate it.
-
get_search_fields()¶ Returns the search field names mapped to weights as a dict. Used in
get_query_setbelow to tellSearchableQuerySetwhich search fields to use. Also used byDisplayableAdminto populate Django admin’ssearch_fieldsattribute.Search fields can be populated via
SearchableManager.__init__, which then get stored inSearchableManager._search_fields, which serves as an approach for defining an explicit set of fields to be used.Alternatively and more commonly,
search_fieldscan be defined on models themselves. In this case, we look at the model and all its base classes, and build up the search fields from all of those, so the search fields are implicitly built up from the inheritence chain.Finally if no search fields have been defined at all, we fall back to any fields that are
CharFieldorTextFieldinstances.
-
search(*args, **kwargs)¶ Proxy to queryset’s search method for the manager’s model and any models that subclass from this manager’s model if the model is abstract.
-
-
class
mezzanine.core.managers.SearchableQuerySet(*args, **kwargs)¶ QuerySet providing main search functionality for
SearchableManager.-
iterator()¶ If search has occurred and no ordering has occurred, decorate each result with the number of search terms so that it can be sorted by the number of occurrence of terms.
-
order_by(*field_names)¶ Mark the filter as being ordered if search has occurred.
-
search(query, search_fields=None)¶ Build a queryset matching words in the given search query, treating quoted terms as exact phrases and taking into account + and - symbols as modifiers controlling which terms to require and exclude.
-
-
mezzanine.core.managers.search_fields_to_dict(fields)¶ In
SearchableQuerySetandSearchableManager, search fields can either be a sequence, or a dict of fields mapped to weights. This function converts sequences to a dict mapped to even weights, so that we’re consistently dealing with a dict of fields mapped to weights, eg: (“title”, “content”) -> {“title”: 1, “content”: 1}
mezzanine.core.views¶
mezzanine.core.forms¶
mezzanine.core.admin¶
mezzanine.core.middleware¶
-
class
mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware¶ Checks for a POST from the admin login view and if authentication is successful and the “site” interface is selected, redirect to the site.
-
class
mezzanine.core.middleware.FetchFromCacheMiddleware¶ Request phase for Mezzanine cache middleware. Return a response from cache if found, othwerwise mark the request for updating the cache in
UpdateCacheMiddleware.
-
class
mezzanine.core.middleware.RedirectFallbackMiddleware¶ Port of Django’s
RedirectFallbackMiddlewarethat uses Mezzanine’s approach for determining the current site.
-
class
mezzanine.core.middleware.SSLRedirectMiddleware¶ Handles redirections required for SSL when
SSL_ENABLEDisTrue.If
SSL_FORCE_HOSTisTrue, and is not the current host, redirect to it.Also ensure URLs defined by
SSL_FORCE_URL_PREFIXESare redirect to HTTPS, and redirect all other URLs to HTTP if on HTTPS.
-
class
mezzanine.core.middleware.SitePermissionMiddleware¶ Marks the current user with a
has_site_permissionwhich is used in place ofuser.is_staffto achieve per-site staff access.
-
class
mezzanine.core.middleware.TemplateForDeviceMiddleware¶ Inserts device-specific templates to the template list.
-
class
mezzanine.core.middleware.TemplateForHostMiddleware¶ Inserts host-specific templates to the template list.
-
class
mezzanine.core.middleware.UpdateCacheMiddleware¶ Response phase for Mezzanine’s cache middleware. Handles caching the response, and then performing the second phase of rendering, for content enclosed by the
nevercachetag.
mezzanine.core.templatetags.mezzanine_tags¶
mezzanine.core.management.commands¶
mezzanine.core.request¶
-
class
mezzanine.core.request.CurrentRequestMiddleware¶ Stores the request in the current thread for global access.
-
mezzanine.core.request.current_request()¶ Retrieves the request from the current thread.
mezzanine.core.tests¶
mezzanine.pages¶
Provides the main structure of a Mezzanine site with a hierarchical tree of pages, each subclassing the Page model to create a content structure.
mezzanine.pages.models¶
-
class
mezzanine.pages.models.BasePage(*args, **kwargs)¶ Exists solely to store
PageManageras the main manager. If it’s defined onPage, a concrete model, then eachPagesubclass loses the custom manager.
-
class
mezzanine.pages.models.Link(*args, **kwargs)¶ A general content type for creating external links in the page menu.
-
class
mezzanine.pages.models.Page(*args, **kwargs)¶ A page in the page tree. This is the base class that custom content types need to subclass.
-
can_add(request)¶ Dynamic
addpermission for content types to override.
-
can_change(request)¶ Dynamic
changepermission for content types to override.
-
can_delete(request)¶ Dynamic
deletepermission for content types to override.
-
description_from_content()¶ Override
Displayable.description_from_contentto load the content type subclass for whensaveis called directly on aPageinstance, so that all fields defined on the subclass are available for generating the description.
-
get_absolute_url()¶ URL for a page - for
Linkpage types, simply return its slug since these don’t have an actual URL pattern. Also handle the special case of the homepage being a page object.
-
get_ascendants(for_user=None)¶ Returns the ascendants for the page. Ascendants are cached in the
_ascendantsattribute, which is populated when the page is loaded viaPage.objects.with_ascendants_for_slug.
-
get_content_model()¶ Provies a generic method of retrieving the instance of the custom content type’s model for this page.
-
classmethod
get_content_models()¶ Return all Page subclasses.
-
get_slug()¶ Recursively build the slug from the chain of parents.
-
overridden()¶ Returns
Trueif the page’s slug has an explicitly defined urlpattern and is therefore considered to be overridden.
-
save(*args, **kwargs)¶ Create the titles field using the titles up the parent chain and set the initial value for ordering.
-
set_helpers(context)¶ Called from the
page_menutemplate tag and assigns a handful of properties based on the current page, that are used within the various types of menus.
-
set_parent(new_parent)¶ Change the parent of this page, changing this page’s slug to match the new parent if necessary.
-
set_slug(new_slug)¶ Changes this page’s slug, and all other pages whose slugs start with this page’s slug.
-
-
class
mezzanine.pages.models.RichTextPage(*args, **kwargs)¶ Implements the default type of page with a single Rich Text content field.
mezzanine.pages.views¶
-
mezzanine.pages.views.admin_page_ordering(request, *args, **kwargs)¶ Updates the ordering of pages via AJAX from within the admin.
-
mezzanine.pages.views.page(request, slug, template=u'pages/page.html', extra_context=None)¶ Select a template for a page and render it. The
extra_contextarg will include apageobject that’s added viamezzanine.pages.middleware.PageMiddleware. The page is loaded via the middleware so that other apps with urlpatterns that match the current page can include a page in their template context. The urlpattern that maps to this view is a catch-all pattern, in which case the page instance will be None, so raise a 404 then.For template selection, a list of possible templates is built up based on the current page. This list is order from most granular match, starting with a custom template for the exact page, then adding templates based on the page’s parent page, that could be used for sections of a site (eg all children of the parent). Finally at the broadest level, a template for the page’s content type (it’s model class) is checked for, and then if none of these templates match, the default pages/page.html is used.
mezzanine.pages.admin¶
mezzanine.pages.middleware¶
-
class
mezzanine.pages.middleware.PageMiddleware¶ Adds a page to the template context for the current response.
If no page matches the URL, and the view function is not the fall-back page view, we try and find the page with the deepest URL that matches within the current URL, as in this situation, the app’s urlpattern is considered to sit “under” a given page, for example the blog page will be used when individual blog posts are viewed. We want the page for things like breadcrumb nav, and page processors, but most importantly so the page’s
login_requiredflag can be honoured.If a page is matched, and the fall-back page view is called, we add the page to the
extra_contextarg of the page view, which it can then use to choose which template to use.In either case, we add the page to the response’s template context, so that the current page is always available.
mezzanine.pages.templatetags.pages_tags¶
Create a select list containing each of the models that subclass the
Pagemodel.
Return a list of child pages for the given parent, storing all pages in a dict in the context when first called using parents as keys for retrieval on subsequent recursive calls from the menu template.
Assigns a permissions dict to the given model, much like Django does with its dashboard app list.
Used within the change list for pages, to implement permission checks for the navigation tree.
Assigns a permissions dict to the given page instance, combining Django’s permission for the page’s model and a permission check against the instance itself calling the page’s
can_add,can_changeandcan_deletecustom methods.Used within the change list for pages, to implement permission checks for the navigation tree.
mezzanine.pages.page_processors¶
-
mezzanine.pages.page_processors.autodiscover()¶ Taken from
django.contrib.admin.autodiscoverand used to run any calls to theprocessor_fordecorator.
-
mezzanine.pages.page_processors.processor_for(content_model_or_slug, exact_page=False)¶ Decorator that registers the decorated function as a page processor for the given content model or slug.
When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in
Truefor theexact_pagearg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed.
mezzanine.generic¶
Provides various models and associated functionality, that can be related to any other model using generic relationshipswith Django’s contenttypes framework, such as comments, keywords/tags and voting.
mezzanine.generic.models¶
mezzanine.generic.managers¶
mezzanine.generic.fields¶
-
class
mezzanine.generic.fields.BaseGenericRelation(*args, **kwargs)¶ Extends
GenericRelationto:- Add a consistent default value for
object_id_fieldand check for arelated_modelattribute which can be defined on subclasses as a default for thetoargument. - Add one or more custom fields to the model that the relation
field is applied to, and then call a
related_items_changedmethod each time related items are saved or deleted, so that a calculated value can be stored against the custom fields since aggregates aren’t available for GenericRelation instances.
-
contribute_to_class(cls, name)¶ Add each of the names and fields in the
fieldsattribute to the model the relationship field is applied to, and set up the related item save and delete signals for callingrelated_items_changed.
-
db_type(connection)¶ South expects this to return a string for initial migrations against MySQL, to check for text or geometery columns. These generic fields are neither of those, but returning an empty string here at least allows migrations to run successfully. See http://south.aeracode.org/ticket/1204
Can be implemented by subclasses - called whenever the state of related items change, eg they’re saved or deleted. The instance for this field and the related manager for the field are passed as arguments.
- Add a consistent default value for
-
class
mezzanine.generic.fields.CommentsField(*args, **kwargs)¶ Stores the number of comments against the
COMMENTS_FIELD_NAME_countfield when a comment is saved or deleted.Stores the number of comments. A custom
count_filterqueryset gets checked for, allowing managers to implement custom count logic.
-
class
mezzanine.generic.fields.KeywordsField(*args, **kwargs)¶ Stores the keywords as a single string into the
KEYWORDS_FIELD_NAME_stringfield for convenient access when searching.-
contribute_to_class(cls, name)¶ Swap out any reference to
KeywordsFieldwith theKEYWORDS_FIELD_stringfield insearch_fields.
-
formfield(**kwargs)¶ Provide the custom form widget for the admin, since there isn’t a form field mapped to
GenericRelationmodel fields.
Stores the keywords as a single string for searching.
-
save_form_data(instance, data)¶ The
KeywordsWidgetfield will return data as a string of comma separated IDs for theKeywordmodel - convert these into actualAssignedKeywordinstances. Also deleteKeywordinstances if their last relatedAssignedKeywordinstance is being removed.
-
-
class
mezzanine.generic.fields.RatingField(*args, **kwargs)¶ Stores the rating count and average against the
RATING_FIELD_NAME_countandRATING_FIELD_NAME_averagefields when a rating is saved or deleted.Calculates and saves the average rating.
mezzanine.generic.views¶
mezzanine.generic.forms¶
mezzanine.generic.admin¶
mezzanine.generic.templatetags.comment_tags¶
mezzanine.generic.templatetags.disqus_tags¶
Returns a unique identifier for the object to be used in DISQUS JavaScript.
Provides a generic context variable which adds single-sign-on support to DISQUS if
COMMENTS_DISQUS_API_PUBLIC_KEYandCOMMENTS_DISQUS_API_SECRET_KEYare specified.
mezzanine.generic.templatetags.keyword_tags¶
mezzanine.generic.templatetags.rating_tags¶
mezzanine.blog¶
Provides a blogging app with posts, keywords, categories and comments. Posts can be listed by month, keyword, category or author.
mezzanine.blog.models¶
-
class
mezzanine.blog.models.BlogCategory(*args, **kwargs)¶ A category for grouping blog posts into a series.
-
class
mezzanine.blog.models.BlogPost(*args, **kwargs)¶ A blog post.
-
get_absolute_url(*args, **kwargs)¶ URLs for blog posts can either be just their slug, or prefixed with a portion of the post’s publish date, controlled by the setting
BLOG_URLS_DATE_FORMAT, which can contain the valueyear,month, orday. Each of these maps to the name of the corresponding urlpattern, and if defined, we loop through each of these and build up the kwargs for the correct urlpattern. The order which we loop through them is important, since the order goes from least granualr (just year) to most granular (year/month/day).
-
mezzanine.blog.views¶
mezzanine.blog.forms¶
mezzanine.blog.admin¶
mezzanine.blog.feeds¶
mezzanine.blog.templatetags.blog_tags¶
mezzanine.blog.management.base¶
mezzanine.blog.management.commands¶
mezzanine.accounts¶
Provides features for non-staff user accounts, such as login, signup
with optional email verification, password reset, and integration
with user profiles models defined by the AUTH_PROFILE_MODULE
setting. Some utility functions for probing the profile model are
included below.
-
mezzanine.accounts.get_profile_form()¶ Returns the profile form defined by
ACCOUNTS_PROFILE_FORM_CLASS.
-
mezzanine.accounts.get_profile_model()¶ Returns the profile model defined by the
AUTH_PROFILE_MODULEsetting, orNoneif no profile model is defined.
-
mezzanine.accounts.get_profile_user_fieldname()¶ Returns the name of the first field on the profile model that points to the
auth.Usermodel.
mezzanine.accounts.views¶
mezzanine.accounts.forms¶
mezzanine.accounts.templatetags.accounts_tags¶
mezzanine.accounts.admin¶
mezzanine.forms¶
A port of django-forms-builder for Mezzanine. Allows admin users to create their own HTML5 forms and export form submissions as CSV.
mezzanine.forms.models¶
mezzanine.forms.forms¶
mezzanine.forms.page_processors¶
mezzanine.forms.admin¶
mezzanine.galleries¶
Implements a photo gallery content type.
mezzanine.galleries.models¶
mezzanine.galleries.admin¶
mezzanine.conf¶
Drop-in replacement for django.conf.settings that provides a
consistent access method for settings defined in applications, the project
or Django itself. Settings can also be made editable via the admin.
-
class
mezzanine.conf.Settings¶ An object that provides settings via dynamic attribute access.
Settings that are registered as editable will be stored in the database once the site settings form in the admin is first saved. When these values are accessed via this settings object, all database stored settings get retrieved from the database.
When accessing uneditable settings their default values are used, unless they’ve been given a value in the project’s settings.py module.
The settings object also provides access to Django settings via
django.conf.settings, in order to provide a consistent method of access for all settings.-
use_editable()¶ Empty the editable settings cache and set the loaded flag to
Falseso that settings will be loaded from the DB on next access. If the conf app is not installed then set the loaded flag toTruein order to bypass DB lookup entirely.
-
-
mezzanine.conf.register_setting(name='', label='', editable=False, description='', default=None, choices=None, append=False)¶ Registers a setting that can be edited via the admin.
mezzanine.conf.models¶
-
class
mezzanine.conf.models.Setting(*args, **kwargs)¶ Stores values for
mezzanine.confthat can be edited via the admin.
mezzanine.conf.forms¶
mezzanine.conf.admin¶
-
class
mezzanine.conf.admin.SettingsAdmin(model, admin_site)¶ Admin class for settings model. Redirect add/change views to the list view where a single form is rendered for editing all settings.
mezzanine.conf.context_processors¶
-
class
mezzanine.conf.context_processors.TemplateSettings¶ Dict wrapper for template settings. This exists only to warn when deprecated settings are accessed in templates.
-
mezzanine.conf.context_processors.settings(request=None)¶ Add the settings object to the template context.
mezzanine.template¶
-
class
mezzanine.template.Library¶ Extends
django.template.Libraryproviding several shortcuts that attempt to take the leg-work out of creating different types of template tags.-
as_tag(tag_func)¶ Creates a tag expecting the format:
{% tag_name as var_name %}The decorated func returns the value that is given tovar_namein the template.
-
inclusion_tag(name, context_class=<class 'django.template.context.Context'>, takes_context=False)¶ Replacement for Django’s
inclusion_tagwhich looks up device specific templates at render time.
-
render_tag(tag_func)¶ Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token.
-
to_end_tag(tag_func)¶ Creates a tag that parses until it finds the corresponding end tag, eg: for a tag named
mytagit will parse untilendmytag. The decorated func’s return value is used to render the parsed content and takes three arguments - the parsed content between the start and end tags, the template context and the tag token.
-
mezzanine.template.loader_tags¶
mezzanine.twitter¶
Provides models and utilities for displaying different types of Twitter feeds.
mezzanine.twitter.models¶
mezzanine.twitter.managers¶
mezzanine.twitter.templatetags.twitter_tags¶
mezzanine.twitter.management.commands¶
mezzanine.utils¶
Various utility functions used throughout the different Mezzanine apps.
-
mezzanine.utils.cache.add_cache_bypass(url)¶ Adds the current time to the querystring of the URL to force a cache reload. Used for when a form post redirects back to a page that should display updated content, such as new comments or ratings.
-
mezzanine.utils.cache.cache_get(key)¶ Wrapper for
cache.get. The expiry time for the cache entry is stored with the entry. If the expiry time has past, put the stale entry back into cache, and don’t return it to trigger a fake cache miss.
-
mezzanine.utils.cache.cache_installed()¶ Returns
Trueif a cache backend is configured, and the cache middlware classes are present.
-
mezzanine.utils.cache.cache_key_prefix(request)¶ Cache key for Mezzanine’s cache middleware. Adds the current device and site ID.
-
mezzanine.utils.cache.cache_set(key, value, timeout=None, refreshed=False)¶ Wrapper for
cache.set. Stores the cache entry packed with the desired cache expiry time. When the entry is retrieved from cache, the packed expiry time is also checked, and if past, the stale cache entry is stored again with an expiry that hasCACHE_SET_DELAY_SECONDSadded to it. In this case the entry is not returned, so that a cache miss occurs and the entry should be set by the caller, but all other callers will still get the stale entry, so no real cache misses ever occur.
-
mezzanine.utils.cache.nevercache_token()¶ Returns the secret token that delimits content wrapped in the
nevercachetemplate tag.
-
mezzanine.utils.device.device_from_request(request)¶ Determine’s the device name from the request by first looking for an overridding cookie, and if not found then matching the user agent. Used at both the template level for choosing the template to load and also at the cache level as a cache key prefix.
-
mezzanine.utils.device.templates_for_device(request, templates)¶ Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted before it’s associate default in the list.
Utils called from project_root/docs/conf.py when Sphinx documentation is generated.
-
mezzanine.utils.docs.build_changelog(docs_path, package_name='mezzanine')¶ Converts Mercurial commits into a changelog in RST format.
-
mezzanine.utils.docs.build_modelgraph(docs_path, package_name='mezzanine')¶ Creates a diagram of all the models for mezzanine and the given package name, generates a smaller version and add it to the docs directory for use in model-graph.rst
-
mezzanine.utils.docs.build_requirements(docs_path, package_name='mezzanine')¶ Updates the requirements file with Mezzanine’s version number.
-
mezzanine.utils.docs.build_settings_docs(docs_path, prefix=None)¶ Converts names, descriptions and defaults for settings in
mezzanine.conf.registryinto RST format for use in docs, optionally filtered by setting names with the given prefix.
-
mezzanine.utils.docs.deep_force_unicode(value)¶ Recursively call force_unicode on value.
-
mezzanine.utils.email.send_approve_mail(request, user)¶ Sends an email to staff in listed in the setting
ACCOUNTS_APPROVAL_EMAILS, when a new user signs up and theACCOUNTS_APPROVAL_REQUIREDsetting isTrue.
-
mezzanine.utils.email.send_approved_mail(request, user)¶ Sends an email to a user once their
is_activestatus goes fromFalsetoTruewhen theACCOUNTS_APPROVAL_REQUIREDsetting isTrue.
-
mezzanine.utils.email.send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=False, addr_bcc=None, headers=None)¶ Send email rendering text and html versions for the specified template name using the context dictionary passed in.
-
mezzanine.utils.email.send_verification_mail(request, user, verification_type)¶ Sends an email with a verification link to users when
ACCOUNTS_VERIFICATION_REQUIREDis`Trueand they’re signing up, or when they reset a lost password. Theverification_typearg is both the name of the urlpattern for the verification link, as well as the names of the email templates to use.
-
mezzanine.utils.email.split_addresses(email_string_list)¶ Converts a string containing comma separated email addresses into a list of email addresses.
-
mezzanine.utils.email.subject_template(template, context)¶ Loads and renders an email subject template, returning the subject string.
-
class
mezzanine.utils.html.TagCloser(html)¶ HTMLParser that closes open tags. Takes a HTML string as its first arg, and populate a
htmlattribute on the parser with the original HTML arg and any required closing tags.
-
mezzanine.utils.html.decode_entities(html)¶ Remove HTML entities from a string. Adapted from http://effbot.org/zone/re-sub.htm#unescape-html
-
mezzanine.utils.importing.import_dotted_path(path)¶ Takes a dotted path to a member name in a module, and returns the member after importing it.
-
mezzanine.utils.importing.path_for_import(name)¶ Returns the directory path for the given package or module.
-
class
mezzanine.utils.models.AdminThumbMixin¶ Provides a thumbnail method on models for admin classes to reference in the
list_displaydefinition.
-
class
mezzanine.utils.models.ModelMixin¶ Used as a subclass for mixin models that inject their behaviour onto models defined outside of a project. The subclass should define an inner
Metaclass with amixin_forattribute containing the model that will be mixed into.
-
class
mezzanine.utils.models.ModelMixinBase¶ Metaclass for
ModelMixinwhich is used for injecting model fields and methods into models defined outside of a project. This currently isn’t used anywhere.
-
mezzanine.utils.models.base_concrete_model(abstract, instance)¶ Used in methods of abstract models to find the super-most concrete (non abstract) model in the inheritance chain that inherits from the given abstract model. This is so the methods in the abstract model can query data consistently across the correct concrete model.
Consider the following:
class Abstract(models.Model) class Meta: abstract = True def concrete(self): return base_concrete_model(Abstract, self) class Super(Abstract): pass class Sub(Super): pass sub = Sub.objects.create() sub.concrete() # returns SuperIn actual Mezzanine usage, this allows methods in the
DisplayableandOrderableabstract models to access thePageinstance when instances of custom content types, (eg: models that inherit fromPage) need to query thePagemodel to determine correct values forslugand_orderwhich are only relevant in the context of thePagemodel and not the model of the custom content type.
-
mezzanine.utils.models.get_user_model_name()¶ Returns the app_label.object_name string for the user model.
-
mezzanine.utils.models.upload_to(field_path, default)¶ Used as the
upload_toarg for file fields - allows for custom handlers to be implemented on a per field basis defined by theUPLOAD_TO_HANDLERSsetting.
-
mezzanine.utils.sites.current_site_id()¶ Responsible for determining the current
Siteinstance to use when retrieving data for anySiteRelatedmodels. If a request is available, and the site can be determined from it, we store the site against the request for subsequent retrievals. Otherwise the order of checks is as follows:site_idin session. Used in the admin so that admin users can switch sites and stay on the same domain for the admin.- host for the current request matched to the domain of the site instance.
MEZZANINE_SITE_IDenvironment variable, so management commands or anything else outside of a request can specify a site.SITE_IDsetting.
-
mezzanine.utils.sites.has_site_permission(user)¶ Checks if a staff user has staff-level access for the current site. The actual permission lookup occurs in
SitePermissionMiddlewarewhich then marks the request with thehas_site_permissionflag, so that we only query the db once per request, so this function serves as the entry point for everything else to check access. We also fall back to anis_staffcheck if the middleware is not installed, to ease migration.
-
mezzanine.utils.sites.host_theme_path(request)¶ Returns the directory of the theme associated with the given host.
-
mezzanine.utils.sites.templates_for_host(request, templates)¶ Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted into the front of the list.
-
mezzanine.utils.urls.admin_url(model, url, object_id=None)¶ Returns the URL for the given model and admin url name.
-
mezzanine.utils.urls.home_slug()¶ Returns the slug arg defined for the
homeurlpattern, which is the definitive source of theurlfield defined for an editable homepage object.
-
mezzanine.utils.urls.login_redirect(request)¶ Returns the redirect response for login/signup. Favors: - next param - LOGIN_REDIRECT_URL setting - homepage
-
mezzanine.utils.urls.next_url(request)¶ Returns URL to redirect to from the
nextparam in the request.
-
mezzanine.utils.urls.path_to_slug(path)¶ Removes everything from the given URL path, including language code and
PAGES_SLUGif any is set, returning a slug that would match aPageinstance’s slug.
-
mezzanine.utils.urls.slugify(s)¶ Loads the callable defined by the
SLUGIFYsetting, which defaults to theslugify_unicodefunction.
-
mezzanine.utils.urls.slugify_unicode(s)¶ Replacement for Django’s slugify which allows unicode chars in slugs, for URLs in Chinese, Russian, etc. Adopted from https://github.com/mozilla/unicode-slugify/
-
mezzanine.utils.urls.unique_slug(queryset, slug_field, slug)¶ Ensures a slug is unique for the given queryset, appending an integer to its end until the slug is unique.
-
mezzanine.utils.views.ip_for_request(request)¶ Returns ip address for request - first checks
HTTP_X_FORWARDED_FORheader, since app will generally be behind a public web server.
-
mezzanine.utils.views.is_editable(obj, request)¶ Returns
Trueif the object is editable for the request. First check for a customeditablehandler on the object, otherwise use the logged in user and check change permissions for the object’s model.
-
mezzanine.utils.views.is_spam(request, form, url)¶ Main entry point for spam handling - called from the comment view and page processor for
mezzanine.forms, to check if posted content is spam. Spam filters are configured via theSPAM_FILTERSsetting.
Identifies form data as being spam, using the http://akismet.com service. The Akismet API key should be specified in the
AKISMET_API_KEYsetting. This function is the default spam handler defined in theSPAM_FILTERSsetting.The name, email, url and comment fields are all guessed from the form fields:
- name: First field labelled “Name”, also taking i18n into account.
- email: First
EmailFieldfield. - url: First
URLFieldfield. - comment: First field with a
Textareawidget.
If the actual comment can’t be extracted, spam checking is passed.
The referrer field expects a hidden form field to pass the referrer through, since the HTTP_REFERER will be the URL the form is posted from. The hidden referrer field is made available by default with the
{% fields_for %}templatetag used for rendering form fields.
-
mezzanine.utils.views.paginate(objects, page_num, per_page, max_paging_links)¶ Return a paginated page for the given objects, giving it a custom
visible_page_rangeattribute calculated frommax_paging_links.
-
mezzanine.utils.views.render(request, templates, dictionary=None, context_instance=None, **kwargs)¶ Mimics
django.shortcuts.renderbut uses a TemplateResponse formezzanine.core.middleware.TemplateForDeviceMiddleware
Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded.