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_FIELDS setting.

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_url defined, 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 use auto_now_add on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard.

set_short_url()

Sets the short_url attribute using the bit.ly credentials if they have been specified, and saves it. Used by the set_short_url_for template tag, and TweetableAdmin.

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_title field, 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 with ForeignKey("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_to value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation’s ct_field and fk_field attributes.

class mezzanine.core.models.OrderableBase

Checks for order_with_respect_to on the model’s inner Meta class and if found, copies it to a custom attribute and deletes it since it will cause errors when used with ForeignKey("self"). Also creates the ordering attribute on the Meta class 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 Site model, and filters by site with all querysets. See mezzanine.utils.sites.current_site_id for implementation details.

save(update_site=False, *args, **kwargs)

Set the site to the current site when the record is first created, or the update_site argument is explicitly set to True.

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.

generate_unique_slug()

Create a unique slug by passing the result of get_slug() to utils.urls.unique_slug, which appends an index if necessary.

get_slug()

Allows subclasses to implement their own slug creation logic.

save(*args, **kwargs)

If no slug is provided, generates one before saving.

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 variable MEZZANINE_SITE_ID (which can be used by management commands with the --site arg, finally falling back to settings.SITE_ID if none of those match a site.

class mezzanine.core.managers.DisplayableManager(field_name=None, *args, **kwargs)

Manually combines CurrentSiteManager, PublishedManager and SearchableManager for the Displayable model.

url_map(for_user=None, **kwargs)

Returns a dictionary of urls mapped to Displayable subclass instances, including a fake homepage instance if none exists. Used in mezzanine.core.sitemaps.

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_set below to tell SearchableQuerySet which search fields to use. Also used by DisplayableAdmin to populate Django admin’s search_fields attribute.

Search fields can be populated via SearchableManager.__init__, which then get stored in SearchableManager._search_fields, which serves as an approach for defining an explicit set of fields to be used.

Alternatively and more commonly, search_fields can 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 CharField or TextField instances.

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.

In the case of search fields that span model relationships, we cannot accurately match occurrences without some very complicated traversal code, which we won’t attempt. So in this case, namely when there are no matches for a result (count=0), and search fields contain relationships (double underscores), we assume one match for one of the fields, and use the average weight of all search fields with relationships.

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 SearchableQuerySet and SearchableManager, 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.views.direct_to_template(request, template, extra_context=None, **kwargs)

Replacement for Django’s direct_to_template that uses TemplateResponse via mezzanine.utils.views.render.

Renders a list of url/title pairs for all Displayable subclass instances into JavaScript that’s used to populate a list of links in TinyMCE.

mezzanine.core.views.edit(request, *args, **kwargs)

Process the inline editing form.

mezzanine.core.views.page_not_found(request, *args, **kwargs)

Mimics Django’s 404 handler but with a different template path.

mezzanine.core.views.search(request, template=u'search_results.html')

Display search results. Takes an optional “contenttype” GET parameter in the form “app-name.ModelName” to limit search results to a single model.

mezzanine.core.views.server_error(request, *args, **kwargs)

Mimics Django’s error handler but adds STATIC_URL to the context.

mezzanine.core.views.set_device(request, device=u'')

Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile).

mezzanine.core.views.set_site(request, *args, **kwargs)

Put the selected site ID into the session - posted to from the “Select site” drop-down in the header of the admin. The site ID is then used in favour of the current request’s domain in mezzanine.core.managers.CurrentSiteManager.

mezzanine.core.views.static_proxy(request, *args, **kwargs)

Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if STATIC_URL is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django.

mezzanine.core.forms

class mezzanine.core.forms.CheckboxSelectMultiple(*args, **kwargs)

Wraps render with a CSS class for styling.

class mezzanine.core.forms.DynamicInlineAdminForm(*args, **kwargs)

Form for DynamicInlineAdmin that can be collapsed and sorted with drag and drop using OrderWidget.

class mezzanine.core.forms.Html5Mixin(*args, **kwargs)

Mixin for form classes. Adds HTML5 features to forms for client side validation by the browser, like a “required” attribute and “email” and “url” input types.

class mezzanine.core.forms.OrderWidget(attrs=None)

Add up and down arrows for ordering controls next to a hidden form field.

class mezzanine.core.forms.SplitSelectDateTimeWidget(attrs=None, date_format=None, time_format=None)

Combines Django’s SelectDateTimeWidget and SelectDateWidget.

class mezzanine.core.forms.TinyMceWidget(*args, **kwargs)

Setup the JS files and targetting CSS class for a textarea to use TinyMCE.

mezzanine.core.forms.get_edit_form(obj, field_names, data=None, files=None)

Returns the in-line editing form for editing a single model field.

mezzanine.core.admin

class mezzanine.core.admin.BaseDynamicInlineAdmin(*args, **kwargs)

Admin inline that uses JS to inject an “Add another” link which when clicked, dynamically reveals another fieldset. Also handles adding the _order field and its widget for models that subclass Orderable.

form

alias of DynamicInlineAdminForm

class mezzanine.core.admin.DisplayableAdmin(*args, **kwargs)

Admin class for subclasses of the abstract Displayable model.

class mezzanine.core.admin.OwnableAdmin(model, admin_site)

Admin class for models that subclass the abstract Ownable model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user.

Remember that this will include the user field in the required fields for the admin change form which may not be desirable. The best approach to solve this is to define a fieldsets attribute that excludes the user field or simple add user to your admin excludes: exclude = ('user',)

get_queryset(request)

Filter the change list by currently logged in user if not a superuser. We also skip filtering if the model for this admin class has been added to the sequence in the setting OWNABLE_MODELS_ALL_EDITABLE, which contains models in the format app_label.object_name, and allows models subclassing Ownable to be excluded from filtering, eg: ownership should not imply permission to edit.

save_form(request, form, change)

Set the object’s owner as the logged in user.

class mezzanine.core.admin.SingletonAdmin(model, admin_site)

Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn’t.

add_view(*args, **kwargs)

Redirect to the change view if the singleton instance exists.

change_view(*args, **kwargs)

If only the singleton instance exists, pass True for singleton into the template which will use CSS to hide the “save and add another” button.

changelist_view(*args, **kwargs)

Redirect to the add view if no records exist or the change view if the singleton instance exists.

handle_save(request, response)

Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid.

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 RedirectFallbackMiddleware that uses Mezzanine’s approach for determining the current site.

class mezzanine.core.middleware.SSLRedirectMiddleware

Handles redirections required for SSL when SSL_ENABLED is True.

If SSL_FORCE_HOST is True, and is not the current host, redirect to it.

Also ensure URLs defined by SSL_FORCE_URL_PREFIXES are 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_permission which is used in place of user.is_staff to 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 nevercache tag.

mezzanine.core.templatetags.mezzanine_tags

mezzanine.core.templatetags.mezzanine_tags.admin_app_list(request)

Adopted from django.contrib.admin.sites.AdminSite.index. Returns a list of lists of models grouped and ordered according to mezzanine.conf.ADMIN_MENU_ORDER. Called from the admin_dropdown_menu template tag as well as the app_list dashboard widget.

mezzanine.core.templatetags.mezzanine_tags.admin_dropdown_menu(parser, token)

Renders the app list for the admin dropdown menu navigation.

mezzanine.core.templatetags.mezzanine_tags.app_list(parser, token)

Renders the app list for the admin dashboard widget.

mezzanine.core.templatetags.mezzanine_tags.compress(parser, token)

Dummy tag for fallback when django-compressor isn’t installed.

mezzanine.core.templatetags.mezzanine_tags.dashboard_column(parser, token)

Takes an index for retrieving the sequence of template tags from mezzanine.conf.DASHBOARD_TAGS to render into the admin dashboard.

mezzanine.core.templatetags.mezzanine_tags.editable(parser, token)

Add the required HTML to the parsed content for in-line editing, such as the icon and edit form if the object is deemed to be editable - either it has an editable method which returns True, or the logged in user has change permissions for the model.

mezzanine.core.templatetags.mezzanine_tags.editable_loader(parser, token)

Set up the required JS/CSS for the in-line editing toolbar and controls.

mezzanine.core.templatetags.mezzanine_tags.errors_for(parser, token)

Renders an alert if the form has any errors.

mezzanine.core.templatetags.mezzanine_tags.fields_for(parser, token)

Renders fields for a form.

mezzanine.core.templatetags.mezzanine_tags.gravatar_url(email, size=32)

Return the full URL for a Gravatar given an email hash.

mezzanine.core.templatetags.mezzanine_tags.ifinstalled(parser, token)

Old-style if tag that renders contents if the given app is installed. The main use case is:

{% ifinstalled app_name %} {% include “app_name/template.html” %} {% endifinstalled %}

so we need to manually pull out all tokens if the app isn’t installed, since if we used a normal if tag with a False arg, the include tag will still try and find the template to include.

mezzanine.core.templatetags.mezzanine_tags.is_installed(app_name)

Returns True if the given app name is in the INSTALLED_APPS setting.

mezzanine.core.templatetags.mezzanine_tags.metablock(parser, token)

Remove HTML tags, entities and superfluous characters from meta blocks.

mezzanine.core.templatetags.mezzanine_tags.nevercache(parser, token)

Dummy fallback nevercache for when caching is not configured.

mezzanine.core.templatetags.mezzanine_tags.pagination_for(parser, token)

Include the pagination template and data for persisting querystring in pagination links. Can also contain a comma separated string of var names in the current querystring to exclude from the pagination links, via the exclude_vars arg.

mezzanine.core.templatetags.mezzanine_tags.recent_actions(parser, token)

Renders the recent actions list for the admin dashboard widget.

mezzanine.core.templatetags.mezzanine_tags.richtext_filter(content)

Deprecated version of richtext_filters above.

mezzanine.core.templatetags.mezzanine_tags.richtext_filters(content)

Takes a value edited via the WYSIWYG editor, and passes it through each of the functions specified by the RICHTEXT_FILTERS setting.

mezzanine.core.templatetags.mezzanine_tags.search_form(parser, token)

Includes the search form with a list of models to use as choices for filtering the search by. Models should be a string with models in the format app_label.model_name separated by spaces. The string all can also be used, in which case the models defined by the SEARCH_MODEL_CHOICES setting will be used.

mezzanine.core.templatetags.mezzanine_tags.set_short_url_for(parser, token)

Sets the short_url attribute of the given model for share links in the template.

mezzanine.core.templatetags.mezzanine_tags.sort_by(items, attr)

General sort filter - sorts by either attribute or key.

mezzanine.core.templatetags.mezzanine_tags.thumbnail(image_url, width, height, quality=95, left=0.5, top=0.5, padding=False, padding_color=u'#fff')

Given the URL to an image, resizes the image using the given width and height on the first time it is requested, and returns the URL to the new resized image. if width or height are zero then original ratio is maintained.

mezzanine.core.templatetags.mezzanine_tags.translate_url(context, language)

Translates the current URL for the given language code, eg:

{% translate_url de %}

mezzanine.core.templatetags.mezzanine_tags.try_url(url_name)

Mimics Django’s url template tag but fails silently. Used for url names in admin templates as these won’t resolve when admin tests are running.

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 PageManager as the main manager. If it’s defined on Page, a concrete model, then each Page subclass loses the custom manager.

A general content type for creating external links in the page menu.

get_absolute_url(*moreargs, **morekwargs)

URL for a page - for Link page 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.

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 add permission for content types to override.

can_change(request)

Dynamic change permission for content types to override.

can_delete(request)

Dynamic delete permission for content types to override.

description_from_content()

Override Displayable.description_from_content to load the content type subclass for when save is called directly on a Page instance, so that all fields defined on the subclass are available for generating the description.

get_absolute_url(*moreargs, **morekwargs)

URL for a page - for Link page 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 _ascendants attribute, which is populated when the page is loaded via Page.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.

get_template_name()

Subclasses can implement this to provide a template to use in mezzanine.pages.views.page.

overridden()

Returns True if 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_menu template 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.

get_absolute_url(*moreargs, **morekwargs)

URL for a page - for Link page 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.

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 request object should have a page attribute that’s added via mezzanine.pages.middleware.PageMiddleware. The page is loaded earlier via middleware to perform various other functions. The urlpattern that maps to this view is a catch-all pattern, in which case the page attribute won’t exist, 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

class mezzanine.pages.admin.PageAdmin(*args, **kwargs)

Admin class for the Page model and all subclasses of Page. Handles redirections between admin interfaces for the Page model and its subclasses.

add_view(request, **kwargs)

For the Page model, redirect to the add view for the first page model, based on the ADD_PAGE_ORDER setting.

change_view(request, object_id, **kwargs)

For the Page model, check page.get_content_model() for a subclass and redirect to its admin change view. Also enforce custom change permissions for the page instance.

changelist_view(request, extra_context=None)

Redirect to the Page changelist view for Page subclasses.

delete_view(request, object_id, **kwargs)

Enforce custom delete permissions for the page instance.

classmethod get_content_models()

Return all Page subclasses that are admin registered, ordered based on the ADD_PAGE_ORDER setting.

in_menu()

Hide subclasses from the admin menu.

response_add(request, obj)

Enforce page permissions and maintain the parent ID in the querystring.

response_change(request, obj)

Enforce page permissions and maintain the parent ID in the querystring.

save_model(request, obj, form, change)

Set the ID of the parent page if passed in via querystring, and make sure the new slug propagates to all descendant pages.

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_required flag can be honoured.

If a page is matched, and the fall-back page view is called, we add the page to the extra_context arg 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.

classmethod installed()

Used in mezzanine.pages.views.page to ensure PageMiddleware or a subclass has been installed. We cache the result on the PageMiddleware._installed to only run this once. Short path is to just check for the dotted path to PageMiddleware in MIDDLEWARE_CLASSES - if not found, we need to load each middleware class to match a subclass.

process_view(request, view_func, view_args, view_kwargs)

Per-request mechanics for the current page object.

mezzanine.pages.templatetags.pages_tags

mezzanine.pages.templatetags.pages_tags.models_for_pages(parser, token)

Create a select list containing each of the models that subclass the Page model.

mezzanine.pages.templatetags.pages_tags.page_menu(parser, token)

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.

mezzanine.pages.templatetags.pages_tags.set_model_permissions(parser, token)

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.

mezzanine.pages.templatetags.pages_tags.set_page_permissions(parser, token)

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_change and can_delete custom 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.autodiscover and used to run any calls to the processor_for decorator.

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 True for the exact_page arg, 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

class mezzanine.generic.models.AssignedKeyword(*args, **kwargs)

A Keyword assigned to a model instance.

class mezzanine.generic.models.Keyword(*args, **kwargs)

Keywords/tags which are managed via a custom JavaScript based widget in the admin.

class mezzanine.generic.models.Rating(*args, **kwargs)

A rating that can be given to a piece of content.

save(*args, **kwargs)

Validate that the rating falls between the min and max values.

class mezzanine.generic.models.ThreadedComment(*args, **kwargs)

Extend the Comment model from django.contrib.comments to add comment threading. Comment provides its own site foreign key, so we can’t inherit from SiteRelated in mezzanine.core, and therefore need to set the site on save. CommentManager inherits from Mezzanine’s CurrentSiteManager, so everything else site related is already provided.

get_absolute_url(*moreargs, **morekwargs)

Use the URL for the comment’s content object, with a URL hash appended that references the individual comment.

save(*args, **kwargs)

Set the current site ID, and is_public based on the setting COMMENTS_DEFAULT_APPROVED.

mezzanine.generic.managers

class mezzanine.generic.managers.CommentManager(field_name=None, *args, **kwargs)

Provides filter for restricting comments that are not approved if COMMENTS_UNAPPROVED_VISIBLE is set to False.

count_queryset()

Called from CommentsField.related_items_changed to store the comment count against an item each time a comment is saved.

visible()

Return the comments that are visible based on the COMMENTS_XXX_VISIBLE settings. When these settings are set to True, the relevant comments are returned that shouldn’t be shown, and are given placeholders in the template generic/includes/comment.html.

mezzanine.generic.fields

class mezzanine.generic.fields.BaseGenericRelation(*args, **kwargs)

Extends GenericRelation to:

  • Add a consistent default value for object_id_field and check for a related_model attribute which can be defined on subclasses as a default for the to argument.
  • Add one or more custom fields to the model that the relation field is applied to, and then call a related_items_changed method 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 fields attribute to the model the relationship field is applied to, and set up the related item save and delete signals for calling related_items_changed.

related_items_changed(instance, related_manager)

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.

class mezzanine.generic.fields.CommentsField(*args, **kwargs)

Stores the number of comments against the COMMENTS_FIELD_NAME_count field when a comment is saved or deleted.

related_items_changed(instance, related_manager)

Stores the number of comments. A custom count_filter queryset 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_string field for convenient access when searching.

contribute_to_class(cls, name)

Swap out any reference to KeywordsField with the KEYWORDS_FIELD_string field in search_fields.

formfield(**kwargs)

Provide the custom form widget for the admin, since there isn’t a form field mapped to GenericRelation model fields.

related_items_changed(instance, related_manager)

Stores the keywords as a single string for searching.

save_form_data(instance, data)

The KeywordsWidget field will return data as a string of comma separated IDs for the Keyword model - convert these into actual AssignedKeyword instances. Also delete Keyword instances if their last related AssignedKeyword instance is being removed.

class mezzanine.generic.fields.RatingField(*args, **kwargs)

Stores the rating count and average against the RATING_FIELD_NAME_count and RATING_FIELD_NAME_average fields when a rating is saved or deleted.

related_items_changed(instance, related_manager)

Calculates and saves the average rating.

mezzanine.generic.views

mezzanine.generic.views.admin_keywords_submit(request, *args, **kwargs)

Adds any new given keywords from the custom keywords field in the admin, and returns their IDs for use when saving a model with a keywords field.

mezzanine.generic.views.comment(request, template=u'generic/comments.html')

Handle a ThreadedCommentForm submission and redirect back to its related object.

mezzanine.generic.views.initial_validation(request, prefix)

Returns the related model instance and post data to use in the comment/rating views below.

Both comments and ratings have a prefix_ACCOUNT_REQUIRED setting. If this is True and the user is unauthenticated, we store their post data in their session, and redirect to login with the view’s url (also defined by the prefix arg) as the next param. We can then check the session data once they log in, and complete the action authenticated.

On successful post, we pass the related object and post data back, which may have come from the session, for each of the comments and ratings view functions to deal with as needed.

mezzanine.generic.views.rating(request)

Handle a RatingForm submission and redirect back to its related object.

mezzanine.generic.forms

class mezzanine.generic.forms.KeywordsWidget(attrs=None)

Form field for the KeywordsField generic relation field. Since the admin with model forms has no form field for generic relations, this form field provides a single field for managing the keywords. It contains two actual widgets, a text input for entering keywords, and a hidden input that stores the ID of each Keyword instance.

The attached JavaScript adds behaviour so that when the form is submitted, an AJAX post is made that passes the list of keywords in the text input, and returns a list of keyword IDs which are then entered into the hidden input before the form submits. The list of IDs in the hidden input is what is used when retrieving an actual value from the field for the form.

decompress(value)

Takes the sequence of AssignedKeyword instances and splits them into lists of keyword IDs and titles each mapping to one of the form field widgets.

format_output(rendered_widgets)

Wraps the output HTML with a list of all available Keyword instances that can be clicked on to toggle a keyword.

value_from_datadict(data, files, name)

Return the comma separated list of keyword IDs for use in KeywordsField.save_form_data().

class mezzanine.generic.forms.RatingForm(request, *args, **kwargs)

Form for a rating. Subclasses CommentSecurityForm to make use of its easy setup for generic relations.

clean()

Check unauthenticated user’s cookie as a light check to prevent duplicate votes.

save()

Saves a new rating - authenticated users can update the value if they’ve previously rated.

mezzanine.generic.admin

class mezzanine.generic.admin.ThreadedCommentAdmin(model, admin_site)

Admin class for comments.

mezzanine.generic.templatetags.comment_tags

mezzanine.generic.templatetags.comment_tags.comment_filter(comment_text)

Passed comment text to be rendered through the function defined by the COMMENT_FILTER setting. If no function is defined (the default), Django’s linebreaksbr and urlize filters are used.

mezzanine.generic.templatetags.comment_tags.comment_thread(parser, token)

Return a list of child comments for the given parent, storing all comments in a dict in the context when first called, using parents as keys for retrieval on subsequent recursive calls from the comments template.

mezzanine.generic.templatetags.comment_tags.comments_for(parser, token)

Provides a generic context variable name for the object that comments are being rendered for.

mezzanine.generic.templatetags.comment_tags.recent_comments(parser, token)

Dashboard widget for displaying recent comments.

mezzanine.generic.templatetags.disqus_tags

mezzanine.generic.templatetags.disqus_tags.disqus_id_for(obj)

Returns a unique identifier for the object to be used in DISQUS JavaScript.

mezzanine.generic.templatetags.disqus_tags.disqus_sso_script(parser, token)

Provides a generic context variable which adds single-sign-on support to DISQUS if COMMENTS_DISQUS_API_PUBLIC_KEY and COMMENTS_DISQUS_API_SECRET_KEY are specified.

mezzanine.generic.templatetags.keyword_tags

mezzanine.generic.templatetags.keyword_tags.keywords_for(parser, token)

Return a list of Keyword objects for the given model instance or a model class. In the case of a model class, retrieve all keywords for all instances of the model and apply a weight attribute that can be used to create a tag cloud.

mezzanine.generic.templatetags.rating_tags

mezzanine.generic.templatetags.rating_tags.rating_for(parser, token)

Provides a generic context variable name for the object that ratings are being rendered for, and the rating form.

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(*moreargs, **morekwargs)

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 value year, month, or day. 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.views.blog_post_detail(request, slug, year=None, month=None, day=None, template=u'blog/blog_post_detail.html')

. Custom templates are checked for using the name blog/blog_post_detail_XXX.html where XXX is the blog posts’s slug.

mezzanine.blog.views.blog_post_feed(request, format, **kwargs)

Blog posts feeds - maps format to the correct feed view.

mezzanine.blog.views.blog_post_list(request, tag=None, year=None, month=None, username=None, category=None, template=u'blog/blog_post_list.html')

Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked for using the name blog/blog_post_list_XXX.html where XXX is either the category slug or author’s username if given.

mezzanine.blog.forms

class mezzanine.blog.forms.BlogPostForm

Model form for BlogPost that provides the quick blog panel in the admin dashboard.

mezzanine.blog.admin

class mezzanine.blog.admin.BlogCategoryAdmin(model, admin_site)

Admin class for blog categories. Hides itself from the admin menu unless explicitly specified.

in_menu()

Hide from the admin menu unless explicitly set in ADMIN_MENU_ORDER.

class mezzanine.blog.admin.BlogPostAdmin(*args, **kwargs)

Admin class for blog posts.

save_form(request, form, change)

Super class ordering is important here - user must get saved first.

mezzanine.blog.feeds

class mezzanine.blog.feeds.PostsAtom(*args, **kwargs)

Atom feed for all blog posts.

class mezzanine.blog.feeds.PostsRSS(*args, **kwargs)

RSS feed for all blog posts.

mezzanine.blog.templatetags.blog_tags

mezzanine.blog.templatetags.blog_tags.blog_authors(parser, token)

Put a list of authors (users) for blog posts into the template context.

mezzanine.blog.templatetags.blog_tags.blog_categories(parser, token)

Put a list of categories for blog posts into the template context.

mezzanine.blog.templatetags.blog_tags.blog_months(parser, token)

Put a list of dates for blog posts into the template context.

mezzanine.blog.templatetags.blog_tags.blog_recent_posts(parser, token)

Put a list of recently published blog posts into the template context. A tag title or slug, category title or slug or author’s username can also be specified to filter the recent posts returned.

Usage:

{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %}
mezzanine.blog.templatetags.blog_tags.quick_blog(parser, token)

Admin dashboard tag for the quick blog form.

mezzanine.blog.management.base

class mezzanine.blog.management.base.BaseImporterCommand(**kwargs)

Base importer command for blogging platform specific management commands to subclass when importing blog posts into Mezzanine. The handle_import method should be overridden to provide the import mechanism specific to the blogging platform being dealt with.

add_comment(post=None, name=None, email=None, pub_date=None, website=None, body=None)

Adds a comment to the post provided.

add_meta(obj, tags, prompt, verbosity, old_url=None)

Adds tags and a redirect for the given obj, which is a blog post or a page.

add_page(title=None, content=None, old_url=None, tags=None, old_id=None, old_parent_id=None)

Adds a page to the list of pages to be imported - used by the Wordpress importer.

add_post(title=None, content=None, old_url=None, pub_date=None, tags=None, categories=None, comments=None)

Adds a post to the post list for processing.

  • title and content are strings for the post.
  • old_url is a string that a redirect will be created for.
  • pub_date is assumed to be a datetime object.
  • tags and categories are sequences of strings.
  • comments is a sequence of dicts - each dict should be the return value of add_comment.
handle(*args, **options)

Processes the converted data into the Mezzanine database correctly.

Attributes:
mezzanine_user: the user to put this data in against date_format: the format the dates are in for posts and comments
handle_import(options)

Should be overridden by subclasses - performs the conversion from the originating data source into the lists of posts and comments ready for processing.

trunc(model, prompt, **fields)

Truncates fields values for the given model. Prompts for a new value if truncation occurs.

mezzanine.blog.management.commands

class mezzanine.blog.management.commands.import_rss.Command(**kwargs)

Import an RSS feed into the blog app.

class mezzanine.blog.management.commands.import_blogger.Command(**kwargs)

Implements a Blogger importer. Takes a Blogger ID in order to be able to determine which blog it should point to and harvest the XML from.

handle_import(options)

Gets posts from Blogger.

class mezzanine.blog.management.commands.import_wordpress.Command(**kwargs)

Implements a Wordpress importer. Takes a file path or a URL for the Wordpress Extended RSS file.

get_text(xml, name, nodetype)

Gets the element’s text value from the XML object provided.

handle_import(options)

Gets the posts from either the provided URL or the path if it is local.

wp_caption(post)

Filters a Wordpress Post for Image Captions and renders to match HTML.

class mezzanine.blog.management.commands.import_tumblr.Command(**kwargs)

Import Tumblr blog posts into the blog app.

mezzanine.blog.management.commands.import_tumblr.title_from_content(content)

Try and extract the first sentence from a block of test to use as a title.

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_MODULE setting, or None if 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.User model.

mezzanine.accounts.views

mezzanine.accounts.views.account_redirect(request, *args, **kwargs)

Just gives the URL prefix for accounts an action - redirect to the profile update form.

mezzanine.accounts.views.login(request, template=u'accounts/account_login.html')

Login form.

mezzanine.accounts.views.logout(request)

Log the user out.

mezzanine.accounts.views.old_account_redirect(request, url_suffix)

Catches and redirects any unmatched account URLs to their correct version (account/ to accounts/) as per #934. The URL is constructed manually, handling slashes as appropriate.

mezzanine.accounts.views.profile(request, username, template=u'accounts/account_profile.html')

Display a profile.

mezzanine.accounts.views.profile_redirect(request, *args, **kwargs)

Just gives the URL prefix for profiles an action - redirect to the logged in user’s profile.

mezzanine.accounts.views.profile_update(request, *args, **kwargs)

Profile update form.

mezzanine.accounts.views.signup(request, template=u'accounts/account_signup.html')

Signup form.

mezzanine.accounts.views.signup_verify(request, uidb36=None, token=None)

View for the link in the verification email sent to a new user when they create an account and ACCOUNTS_VERIFICATION_REQUIRED is set to True. Activates the user and logs them in, redirecting to the URL they tried to access when signing up.

mezzanine.accounts.forms

class mezzanine.accounts.forms.LoginForm(*args, **kwargs)

Fields for login.

clean()

Authenticate the given username/email and password. If the fields are valid, store the authenticated user for returning via save().

save()

Just return the authenticated user - used for logging in.

class mezzanine.accounts.forms.PasswordResetForm(*args, **kwargs)

Validates the user’s username or email for sending a login token for authenticating to change their password.

save()

Just return the authenticated user - used for sending login email.

class mezzanine.accounts.forms.ProfileForm(*args, **kwargs)

ModelForm for auth.User - used for signup and profile update. If a Profile model is defined via AUTH_PROFILE_MODULE, its fields are injected into the form.

clean_email()

Ensure the email address is not already registered.

clean_password2()

Ensure the password fields are equal, and match the minimum length defined by ACCOUNTS_MIN_PASSWORD_LENGTH.

clean_username()

Ensure the username doesn’t exist or contain invalid chars. We limit it to slugifiable chars since it’s used as the slug for the user’s profile view.

save(*args, **kwargs)

Create the new user. If no username is supplied (may be hidden via ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS or ACCOUNTS_NO_USERNAME), we generate a unique username, so that if profile pages are enabled, we still have something to use as the profile’s slug.

mezzanine.accounts.templatetags.accounts_tags

mezzanine.accounts.templatetags.accounts_tags.login_form(parser, token)

Returns the login form:

{% login_form as form %} {{ form }}

mezzanine.accounts.templatetags.accounts_tags.profile_fields(user)

Returns profile fields as a dict for the given user. Used in the profile view template when the ACCOUNTS_PROFILE_VIEWS_ENABLED setting is set to True, and also in the account approval emails sent to administrators when the ACCOUNTS_APPROVAL_REQUIRED setting is set to True.

mezzanine.accounts.templatetags.accounts_tags.profile_form(parser, token)

Returns the profile form for a user:

{% if request.user.is_authenticated %} {% profile_form request.user as form %} {{ form }} {% endif %}

mezzanine.accounts.templatetags.accounts_tags.signup_form(parser, token)

Returns the signup form:

{% signup_form as form %} {{ form }}

mezzanine.accounts.templatetags.accounts_tags.username_or(user, attr)

Returns the user’s username for display, or an alternate attribute if ACCOUNTS_NO_USERNAME is set to True.

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

class mezzanine.forms.models.Field(*args, **kwargs)

A field for a user-built form.

get_choices()

Parse a comma separated choice string into a list of choices taking into account quoted choices.

is_a(*args)

Helper that returns True if the field’s type is given in any arg.

class mezzanine.forms.models.FieldEntry(*args, **kwargs)

A single field value for a form entry submitted via a user-built form.

class mezzanine.forms.models.FieldManager

Only show visible fields when displaying actual form..

class mezzanine.forms.models.Form(*args, **kwargs)

A user-built form.

get_absolute_url(*moreargs, **morekwargs)

URL for a page - for Link page 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.

class mezzanine.forms.models.FormEntry(*args, **kwargs)

An entry submitted via a user-built form.

mezzanine.forms.forms

class mezzanine.forms.forms.EntriesForm(form, request, *args, **kwargs)

Form with a set of fields dynamically assigned that can be used to filter entries for the given forms.models.Form instance.

columns()

Returns the list of selected column names.

rows(csv=False)

Returns each row based on the selected criteria.

class mezzanine.forms.forms.FormForForm(form, context, *args, **kwargs)

Form with a set of fields dynamically assigned, directly based on the given forms.models.Form instance.

email_to()

Return the value entered for the first field of type forms.fields.EMAIL.

save(**kwargs)

Create a FormEntry instance and related FieldEntry instances for each form field.

mezzanine.forms.page_processors

mezzanine.forms.page_processors.form_processor(request, page)

Display a built form and handle submission.

mezzanine.forms.page_processors.format_value(value)

Convert a list into a comma separated string, for displaying select multiple values in emails.

mezzanine.forms.admin

class mezzanine.forms.admin.FieldAdmin(*args, **kwargs)

Admin class for the form field. Inherits from TabularDynamicInlineAdmin to add dynamic “Add another” link and drag/drop ordering.

model

alias of Field

class mezzanine.forms.admin.FormAdmin(*args, **kwargs)

Admin class for the Form model. Includes the urls & views for exporting form entries as CSV and downloading files uploaded via the forms app.

entries_view(request, form_id)

Displays the form entries in a HTML table with option to export as CSV file.

file_view(request, field_entry_id)

Output the file for the requested field entry.

get_urls()

Add the entries view to urls.

mezzanine.galleries

Implements a photo gallery content type.

mezzanine.galleries.models

class mezzanine.galleries.models.Gallery(*args, **kwargs)

Page bucket for gallery photos.

get_absolute_url(*moreargs, **morekwargs)

URL for a page - for Link page 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.

save(delete_zip_import=True, *args, **kwargs)

If a zip file is uploaded, extract any images from it and add them to the gallery, before removing the zip file.

class mezzanine.galleries.models.GalleryImage(*args, **kwargs)

GalleryImage(id, _order, gallery_id, file, description)

save(*args, **kwargs)

If no description is given when created, create one from the file name.

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 False so that settings will be loaded from the DB on next access. If the conf app is not installed then set the loaded flag to True in order to bypass DB lookup entirely.

mezzanine.conf.register_setting(name=None, label=None, editable=False, description=None, default=None, choices=None, append=False)

Registers a setting that can be edited via the admin. This mostly equates to storing the given args as a dict in the registry dict by name.

mezzanine.conf.models

class mezzanine.conf.models.Setting(*args, **kwargs)

Stores values for mezzanine.conf that can be edited via the admin.

mezzanine.conf.forms

class mezzanine.conf.forms.SettingsForm(*args, **kwargs)

Form for settings - creates a field for each setting in mezzanine.conf that is marked as editable.

format_help(description)

Format the setting’s description into HTML.

save()

Save each of the settings to the DB.

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.Library providing 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 to var_name in the template.

inclusion_tag(name, context_class=<class 'django.template.context.Context'>, takes_context=False)

Replacement for Django’s inclusion_tag which 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 mytag it will parse until endmytag. 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

class mezzanine.template.loader_tags.OverExtendsNode(nodelist, parent_name, template_dirs=None)

Allows the template foo/bar.html to extend foo/bar.html, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templates that extend other app templates with the same relative name/path.

We use our own version of find_template, that uses an explict list of template directories to search for the template, based on the directories that the known template loaders (app_directories and filesystem) use. This list gets stored in the template context, and each time a template is found, its absolute path gets removed from the list, so that subsequent searches for the same relative name/path can find parent templates in other directories, which allows circular inheritance to occur.

Django’s app_directories, filesystem, and cached loaders are supported. The eggs loader, and any loader that implements load_template_source with a source string returned, should also theoretically work.

find_template(name, context, peeking=False)

Replacement for Django’s find_template that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name/path to be discovered, so that circular template inheritance can occur.

get_parent(context)

Load the parent template using our own find_template, which will cause its absolute path to not be used again. Then peek at the first node, and if its parent arg is the same as the current parent arg, we know circular inheritance is going to occur, in which case we try and find the template again, with the absolute directory removed from the search list.

mezzanine.template.loader_tags.overextends(parser, token)

Extended version of Django’s extends tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once.

mezzanine.twitter

Provides models and utilities for displaying different types of Twitter feeds.

mezzanine.twitter.models

class mezzanine.twitter.models.Query(*args, **kwargs)

Query(id, type, value, interested)

run()

Request new tweets from the Twitter API.

class mezzanine.twitter.models.Tweet(*args, **kwargs)

Tweet(id, remote_id, created_at, text, profile_image_url, user_name, full_name, retweeter_profile_image_url, retweeter_user_name, retweeter_full_name, query_id)

mezzanine.twitter.managers

class mezzanine.twitter.managers.TweetManager

Manager that handles generating the initial Query instance for a user, list or search term.

get_for(query_type, value)

Create a query and run it for the given arg if it doesn’t exist, and return the tweets for the query.

mezzanine.twitter.templatetags.twitter_tags

mezzanine.twitter.templatetags.twitter_tags.tweets_default(parser, token)

Tweets for the default settings.

mezzanine.twitter.templatetags.twitter_tags.tweets_for(query_type, args, per_user=None)

Retrieve tweets for a user, list or search term. The optional per_user arg limits the number of tweets per user, for example to allow a fair spread of tweets per user for a list.

mezzanine.twitter.templatetags.twitter_tags.tweets_for_list(parser, token)

Tweets for a user’s list.

Tweets for a search query.

mezzanine.twitter.templatetags.twitter_tags.tweets_for_user(parser, token)

Tweets for a user.

mezzanine.twitter.management.commands

class mezzanine.twitter.management.commands.poll_twitter.Command

Polls the Twitter API for tweets associated to the queries in templates.

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 True if 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 has CACHE_SET_DELAY_SECONDS added 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 nevercache template tag.

class mezzanine.utils.conf.SitesAllowedHosts

This is a fallback for Django 1.5’s ALLOWED_HOSTS setting which is required when DEBUG is False. It looks up the Site model and uses any domains added to it, the first time the setting is accessed.

mezzanine.utils.conf.set_dynamic_settings(s)

Called at the end of the project’s settings module, and is passed its globals dict for updating with some final tweaks for settings that generally aren’t specified, but can be given some better defaults based on other settings that have been specified. Broken out into its own function so that the code need not be replicated in the settings modules of other project-based apps that leverage Mezzanine’s settings module.

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=u'mezzanine')

Converts Mercurial commits into a changelog in RST format.

mezzanine.utils.docs.build_modelgraph(docs_path, package_name=u'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=u'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.registry into 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_text 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 the ACCOUNTS_APPROVAL_REQUIRED setting is True.

mezzanine.utils.email.send_approved_mail(request, user)

Sends an email to a user once their is_active status goes from False to True when the ACCOUNTS_APPROVAL_REQUIRED setting is True.

mezzanine.utils.email.send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, 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_REQUIRED is `True and they’re signing up, or when they reset a lost password. The verification_type arg 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 html attribute 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_display definition.

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 Meta class with a mixin_for attribute containing the model that will be mixed into.

class mezzanine.utils.models.ModelMixinBase

Metaclass for ModelMixin which 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 Super

In actual Mezzanine usage, this allows methods in the Displayable and Orderable abstract models to access the Page instance when instances of custom content types, (eg: models that inherit from Page) need to query the Page model to determine correct values for slug and _order which are only relevant in the context of the Page model 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_to arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the UPLOAD_TO_HANDLERS setting.

mezzanine.utils.sites.current_site_id()

Responsible for determining the current Site instance to use when retrieving data for any SiteRelated models. 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_id in 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_ID environment variable, so management commands or anything else outside of a request can specify a site.
  • SITE_ID setting.
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 SitePermissionMiddleware which then marks the request with the has_site_permission flag, 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 an is_staff check 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.

class mezzanine.utils.tests.TestCase(methodName='runTest')

This is the base test case providing common features for all tests across the different apps in Mezzanine.

create_recursive_objects(model, parent_field, **kwargs)

Create multiple levels of recursive objects.

queries_used_for_template(template, **context)

Return the number of queries used when rendering a template string.

setUp()

Creates an admin user and sets up the debug cursor, so that we can track the number of queries used in various places.

tearDown()

Clean up the admin user created and debug cursor.

mezzanine.utils.tests.copy_test_to_media(module, name)

Copies a file from Mezzanine’s test data path to MEDIA_ROOT. Used in tests and demo fixtures.

mezzanine.utils.tests.run_pep8_for_package(package_name, extra_ignore=None)

If pep8 is installed, run it across the given package name returning any warnings or errors found.

mezzanine.utils.tests.run_pyflakes_for_package(package_name, extra_ignore=None)

If pyflakes is installed, run it across the given package name returning any warnings found.

mezzanine.utils.timezone.get_best_local_timezone()

Compares local timezone offset to pytz’s timezone db, to determine a matching timezone name to use when TIME_ZONE is not set.

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 home urlpattern, which is the definitive source of the url field 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 next param in the request.

mezzanine.utils.urls.path_to_slug(path)

Removes everything from the given URL path, including language code and PAGES_SLUG if any is set, returning a slug that would match a Page instance’s slug.

mezzanine.utils.urls.slugify(s)

Loads the callable defined by the SLUGIFY setting, which defaults to the slugify_unicode function.

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_FOR header, since app will generally be behind a public web server.

mezzanine.utils.views.is_editable(obj, request)

Returns True if the object is editable for the request. First check for a custom editable handler 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 the SPAM_FILTERS setting.

mezzanine.utils.views.is_spam_akismet(request, form, url)

Identifies form data as being spam, using the http://akismet.com service. The Akismet API key should be specified in the AKISMET_API_KEY setting. This function is the default spam handler defined in the SPAM_FILTERS setting.

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 EmailField field.
  • url: First URLField field.
  • comment: First field with a Textarea widget.

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_range attribute calculated from max_paging_links.

mezzanine.utils.views.render(request, templates, dictionary=None, context_instance=None, **kwargs)

Mimics django.shortcuts.render but uses a TemplateResponse for mezzanine.core.middleware.TemplateForDeviceMiddleware

Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded.

Table Of Contents

Previous topic

Twitter Integration

Next topic

Colophon

This Page