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)[source]

Injects custom fields onto the given sender model as defined by the EXTRA_MODEL_FIELDS setting. This is a closure over the “fields” variable.

mezzanine.boot.autodiscover(*args, **kwargs)[source]

Replaces django’s original autodiscover to add a call to LazyAdminSite’s lazy_registration.

mezzanine.boot.import_field(field_classpath)[source]

Imports a field by its dotted class path, prepending “django.db.models” to raw class names and raising an exception if the import fails.

mezzanine.boot.parse_extra_model_fields(extra_model_fields)[source]

Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model and instantiating the extra fields. Returns a sequence of tuples of the form (model_key, fields) where model_key is a pair of app_label, model_name and fields is a list of (field_name, field_instance) pairs.

mezzanine.boot.parse_field_path(field_path)[source]

Take a path to a field like “mezzanine.pages.models.Page.feature_image” and return a model key, which is a tuple of the form (‘pages’, ‘page’), and a field name, e.g. “feature_image”.

mezzanine.core

Provides abstract models and admin features used throughout the various Mezzanine apps.

mezzanine.core.models

class mezzanine.core.models.ContentTyped(*args, **kwargs)[source]

Mixin for models that can be subclassed to create custom types. In order to use them:

  • Inherit model from ContentTyped.
  • Call the set_content_model() method in the model’s save() method.
  • Inherit that model’s ModelAdmin from ContentTypesAdmin.
  • Include “admin/includes/content_typed_change_list.html” in the

change_list.html template.

get_content_model()[source]

Return content model, or if this is the base class return it.

classmethod get_content_model_name()[source]

Return the name of the OneToOneField django automatically creates for child classes in multi-table inheritance.

classmethod get_content_models()[source]

Return all subclasses of the concrete model.

set_content_model()[source]

Set content_model to the child class’s related name, or None if this is the base class.

class mezzanine.core.models.Displayable(*args, **kwargs)[source]

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.

generate_short_url()[source]

Returns a new short URL generated using bit.ly if credentials for the service have been specified.

get_absolute_url()[source]

Raise an error if called on a subclass without get_absolute_url defined, to ensure all search results contains a URL.

get_absolute_url_with_host()[source]

Returns host + get_absolute_url - used by the various short_url mechanics below.

Technically we should use self.site.domain, here, however if we were to invoke the short_url mechanics on a list of data (eg blog post list view), we’d trigger a db query per item. Using current_request should provide the same result, since site related data should only be loaded based on the current host anyway.

get_next_by_publish_date(**kwargs)[source]

Retrieves next object by publish date.

get_previous_by_publish_date(**kwargs)[source]

Retrieves previous object by publish date.

publish_date_since()[source]

Returns the time since publish_date.

published()[source]

For non-staff users, return True when status is published and the publish and expiry dates fall before and after the current date when specified.

save(*args, **kwargs)[source]

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()[source]

Generates the short_url attribute if the model does not already have one. Used by the set_short_url_for template tag and TweetableAdmin.

If no sharing service is defined (bitly is the one implemented, but others could be by overriding generate_short_url), the SHORT_URL_UNSET marker gets stored in the DB. In this case, short_url is temporarily (eg not persisted) set to host + get_absolute_url - this is so that we don’t permanently store get_absolute_url, since it may change over time.

class mezzanine.core.models.MetaData(*args, **kwargs)[source]

Abstract model that provides meta data for content.

description_from_content()[source]

Returns the first block or sentence of the first content-like field.

meta_title()[source]

Accessor for the optional _meta_title field, which returns the string version of the instance if not provided.

save(*args, **kwargs)[source]

Set the description field on save.

class mezzanine.core.models.Orderable(*args, **kwargs)[source]

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)[source]

Update the ordering values for siblings.

get_next_by_order(**kwargs)[source]

Retrieves next object by order.

get_previous_by_order(**kwargs)[source]

Retrieves previous object by order.

save(*args, **kwargs)[source]

Set the initial ordering value.

with_respect_to()[source]

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[source]

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)[source]

Abstract model that provides ownership of an object for a user.

is_editable(request)[source]

Restrict in-line editing to the objects’s owner and superusers.

class mezzanine.core.models.RichText(*args, **kwargs)[source]

Provides a Rich Text field for managing general content and making it searchable.

class mezzanine.core.models.SitePermission(*args, **kwargs)[source]

Permission relationship between a user and a site that’s used instead of User.is_staff, for admin and inline-editing access.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.core.models.SiteRelated(*args, **kwargs)[source]

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)[source]

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)[source]

Abstract model that handles auto-generating slugs. Each slugged object is also affiliated with a specific site object.

generate_unique_slug()[source]

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

get_slug()[source]

Allows subclasses to implement their own slug creation logic.

save(*args, **kwargs)[source]

If no slug is provided, generates one before saving.

class mezzanine.core.models.TimeStamped(*args, **kwargs)[source]

Provides created and updated timestamps on models.

mezzanine.core.managers

class mezzanine.core.managers.CurrentSiteManager(field_name=None, *args, **kwargs)[source]

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.

get_queryset()[source]

Returns a new QuerySet object. Subclasses can override this method to easily customize the behavior of the Manager.

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

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

url_map(for_user=None, **kwargs)[source]

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.ManagerDescriptor(manager)[source]

This class exists purely to skip the abstract model check in the __get__ method of Django’s ManagerDescriptor.

class mezzanine.core.managers.PublishedManager[source]

Provides filter for restricting items returned by status and publish date when the given user is not a staff member.

published(for_user=None)[source]

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)[source]

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)[source]

Newer versions of Django explicitly prevent managers being accessed from abstract classes, which is behaviour the search API has always relied on. Here we reinstate it.

get_queryset()[source]

Returns a new QuerySet object. Subclasses can override this method to easily customize the behavior of the Manager.

get_search_fields()[source]

Returns the search field names mapped to weights as a dict. Used in get_queryset 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)[source]

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)[source]

QuerySet providing main search functionality for SearchableManager.

annotate_scores()[source]

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)[source]

Mark the filter as being ordered if search has occurred.

search(query, search_fields=None)[source]

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)[source]

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)[source]

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 JSON that’s used to populate a list of links in TinyMCE.

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

Process the inline editing form.

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

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

mezzanine.core.views.search(request, template=u'search_results.html', extra_context=None)[source]

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)[source]

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

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

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)[source]

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(attrs=None, choices=())[source]

Wraps render with a CSS class for styling.

class mezzanine.core.forms.DynamicInlineAdminForm(data=None, files=None, auto_id=u'id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None)[source]

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

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

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)[source]

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)[source]

Combines Django’s SelectDateTimeWidget and SelectDateWidget.

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

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)[source]

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

mezzanine.core.admin

class mezzanine.core.admin.BaseDynamicInlineAdmin[source]

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 mezzanine.core.forms.DynamicInlineAdminForm

get_fields(request, obj=None)[source]

For subclasses of Orderable, the _order field must always be present and be the last field.

get_fieldsets(request, obj=None)[source]

Same as above, but for fieldsets.

class mezzanine.core.admin.BaseTranslationModelAdmin(model, admin_site)[source]

Abstract class used to handle the switch between translation and no-translation class logic. We define the basic structure for the Media class so we can extend it consistently regardless of whether or not modeltranslation is used.

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

Admin class for subclasses of the abstract Displayable model.

check_permission(request, page, permission)[source]

Subclasses can define a custom permission check and raise an exception if False.

save_model(request, obj, form, change)[source]

Save model for every language so that field auto-population is done for every each of it.

class mezzanine.core.admin.OwnableAdmin(model, admin_site)[source]

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)[source]

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)[source]

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

class mezzanine.core.admin.SiteRedirectAdmin(model, admin_site)[source]

Subclass of Django’s redirect admin that modifies it to behave the way most other admin classes do it Mezzanine with regard to site filtering. It filters the list view by current site, hides the site field from the change form, and assigns the current site to the redirect when first created.

get_queryset(request)[source]

Filters the list view by current site.

save_form(request, form, change)[source]

Assigns the current site to the redirect when first created.

mezzanine.core.middleware

class mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware(get_response=None)[source]

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(get_response=None)[source]

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(*args, **kwargs)[source]

Port of Django’s RedirectFallbackMiddleware that uses Mezzanine’s approach for determining the current site.

class mezzanine.core.middleware.SSLRedirectMiddleware(*args)[source]

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(get_response=None)[source]

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(*args, **kwargs)[source]

DEPRECATED: Device detection has been removed from Mezzanine. Inserts device-specific templates to the template list.

class mezzanine.core.middleware.TemplateForHostMiddleware(*args, **kwargs)[source]

Inserts host-specific templates to the template list.

class mezzanine.core.middleware.UpdateCacheMiddleware(get_response=None)[source]

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)[source]

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(context)[source]

Renders the app list for the admin dropdown menu navigation.

mezzanine.core.templatetags.mezzanine_tags.app_list(context)[source]

Renders the app list for the admin dashboard widget.

mezzanine.core.templatetags.mezzanine_tags.compress(parser, token)[source]

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

mezzanine.core.templatetags.mezzanine_tags.dashboard_column(parser, token)[source]

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)[source]

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(context)[source]

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

mezzanine.core.templatetags.mezzanine_tags.errors_for(form)[source]

Renders an alert if the form has any errors.

mezzanine.core.templatetags.mezzanine_tags.fields_for(context, form, template=u'includes/form_fields.html')[source]

Renders fields for a form with an optional template choice.

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

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

mezzanine.core.templatetags.mezzanine_tags.ifinstalled(parser, token)[source]

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)[source]

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

mezzanine.core.templatetags.mezzanine_tags.metablock(parser, token)[source]

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

mezzanine.core.templatetags.mezzanine_tags.pagination_for(context, current_page, page_var=u'page', exclude_vars=u'')[source]

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(context)[source]

Renders the recent actions list for the admin dashboard widget.

mezzanine.core.templatetags.mezzanine_tags.richtext_filters(content)[source]

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(context, search_model_names=None)[source]

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)[source]

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

mezzanine.core.templatetags.mezzanine_tags.sort_by(items, attr)[source]

General sort filter - sorts by either attribute or key.

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

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. When upscale is False, images smaller than the given size will not be grown to fill that size. The given width and height thus act as maximum dimensions.

mezzanine.core.templatetags.mezzanine_tags.translate_url(context, language)[source]

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

{% translate_url “de” %}
mezzanine.core.templatetags.mezzanine_tags.try_url(url_name)[source]

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(get_response=None)[source]

Stores the request in the current thread for global access.

mezzanine.core.request.current_request()[source]

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)[source]

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.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.pages.models.Page(*args, **kwargs)[source]

A page in the page tree. This is the base class that custom content types need to subclass.

exception DoesNotExist
exception MultipleObjectsReturned
can_add(request)[source]

Dynamic add permission for content types to override.

can_change(request)[source]

Dynamic change permission for content types to override.

can_delete(request)[source]

Dynamic delete permission for content types to override.

can_move(request, new_parent)[source]

Dynamic move permission for content types to override. Controls whether a given page move in the page tree is permitted. When the permission is denied, raises a PageMoveException with a single argument (message explaining the reason).

description_from_content()[source]

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()[source]

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)[source]

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_slug()[source]

Recursively build the slug from the chain of parents.

get_template_name()[source]

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

overridden()[source]

Returns True if the page’s slug has an explicitly defined urlpattern and is therefore considered to be overridden.

save(*args, **kwargs)[source]

Create the titles field using the titles up the parent chain and set the initial value for ordering.

set_helpers(context)[source]

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)[source]

Change the parent of this page, changing this page’s slug to match the new parent if necessary.

set_slug(new_slug)[source]

Changes this page’s slug, and all other pages whose slugs start with this page’s slug.

exception mezzanine.pages.models.PageMoveException(msg=None)[source]

Raised by can_move() when the move permission is denied. Takes an optinal single argument: a message explaining the denial.

class mezzanine.pages.models.RichTextPage(*args, **kwargs)[source]

Implements the default type of page with a single Rich Text content field.

exception DoesNotExist
exception MultipleObjectsReturned

mezzanine.pages.views

mezzanine.pages.views.admin_page_ordering(request, *args, **kwargs)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Enforce custom permissions for the page instance.

check_permission(request, page, permission)[source]

Runs the custom permission check and raises an exception if False.

delete_view(request, object_id, **kwargs)[source]

Enforce custom delete permissions for the page instance.

get_content_models()[source]

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

response_add(request, obj)[source]

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

response_change(request, obj)[source]

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

save_model(request, obj, form, change)[source]

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(*args, **kwargs)[source]

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()[source]

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.

process_view(request, view_func, view_args, view_kwargs)[source]

Per-request mechanics for the current page object.

mezzanine.pages.templatetags.pages_tags

mezzanine.pages.templatetags.pages_tags.models_for_pages(parser, token)[source]

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

mezzanine.pages.templatetags.pages_tags.page_menu(parser, token)[source]

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)[source]

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)[source]

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()[source]

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)[source]

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)[source]

A Keyword assigned to a model instance.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.generic.models.Keyword(*args, **kwargs)[source]

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

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.generic.models.Rating(*args, **kwargs)[source]

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

exception DoesNotExist
exception MultipleObjectsReturned
save(*args, **kwargs)[source]

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

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

Extend the Comment model from django_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.

exception DoesNotExist
exception MultipleObjectsReturned
get_absolute_url()[source]

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

save(*args, **kwargs)[source]

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)[source]

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

count_queryset()[source]

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

visible()[source]

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)[source]

Extends GenericRelation to:

  • Add a consistent default value for object_id_field and check for a default_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)[source]

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)[source]

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.

value_from_object(obj)[source]

Returns the value of this field in the given model instance. See: https://code.djangoproject.com/ticket/22552

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

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)[source]

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)[source]

Stores the keywords as a single string into the KEYWORDS_FIELD_NAME_string field for convenient access when searching.

contribute_to_class(cls, name)[source]

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

formfield(**kwargs)[source]

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)[source]

Stores the keywords as a single string for searching.

save_form_data(instance, data)[source]

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)[source]

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)[source]

Calculates and saves the average rating.

mezzanine.generic.views

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

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', extra_context=None)[source]

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

mezzanine.generic.views.initial_validation(request, prefix)[source]

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)[source]

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

mezzanine.generic.forms

class mezzanine.generic.forms.KeywordsWidget(attrs=None)[source]

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)[source]

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. If the page has encountered a validation error then Takes a string with Keyword ids and fetches the sequence of AssignedKeyword

render(*args, **kwargs)[source]

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)[source]

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

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

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

clean()[source]

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

save()[source]

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

class mezzanine.generic.forms.ThreadedCommentForm(request, *args, **kwargs)[source]
check_for_duplicate_comment(new)[source]

We handle duplicates inside save, since django_comments’ check_for_duplicate_comment doesn’t deal with extra fields defined on the comment model.

get_comment_model()[source]

Use the custom comment model instead of the built-in one.

save(request)[source]

Saves a new comment and sends any notification emails.

mezzanine.generic.admin

class mezzanine.generic.admin.ThreadedCommentAdmin(model, admin_site)[source]

Admin class for comments.

mezzanine.generic.templatetags.comment_tags

mezzanine.generic.templatetags.comment_tags.comment_filter(comment_text)[source]

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(context, parent)[source]

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(context, obj)[source]

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

mezzanine.generic.templatetags.comment_tags.recent_comments(context)[source]

Dashboard widget for displaying recent comments.

mezzanine.generic.templatetags.disqus_tags

mezzanine.generic.templatetags.disqus_tags.disqus_id_for(obj)[source]

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

mezzanine.generic.templatetags.disqus_tags.disqus_sso_script(context)[source]

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)[source]

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(context, obj)[source]

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)[source]

A category for grouping blog posts into a series.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.blog.models.BlogPost(*args, **kwargs)[source]

A blog post.

exception DoesNotExist
exception MultipleObjectsReturned
get_absolute_url()[source]

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 granular (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', extra_context=None)[source]

. 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)[source]

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', extra_context=None)[source]

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[source]

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)[source]

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

has_module_permission(request)[source]

Hide from the admin menu unless explicitly set in ADMIN_MENU_ORDER.

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

Admin class for blog posts.

save_form(request, form, change)[source]

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

mezzanine.blog.feeds

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

Atom feed for all blog posts.

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

RSS feed for all blog posts.

mezzanine.blog.templatetags.blog_tags

mezzanine.blog.templatetags.blog_tags.blog_authors(parser, token)[source]

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

mezzanine.blog.templatetags.blog_tags.blog_categories(parser, token)[source]

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

mezzanine.blog.templatetags.blog_tags.blog_months(parser, token)[source]

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

mezzanine.blog.templatetags.blog_tags.blog_recent_posts(parser, token)[source]

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(context)[source]

Admin dashboard tag for the quick blog form.

mezzanine.blog.management.base

class mezzanine.blog.management.base.BaseImporterCommand(**kwargs)[source]

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)[source]

Adds a comment to the post provided.

add_meta(obj, tags, prompt, verbosity, old_url=None)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Import an RSS feed into the blog app.

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

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)[source]

Gets posts from Blogger.

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

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

get_text(xml, name)[source]

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

handle_import(options)[source]

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

wp_caption(post)[source]

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

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

Import Tumblr blog posts into the blog app.

mezzanine.blog.management.commands.import_tumblr.title_from_content(content)[source]

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 ACCOUNTS_PROFILE_MODEL setting. Some utility functions for probing the profile model are included below.

exception mezzanine.accounts.ProfileNotConfigured[source]
mezzanine.accounts.get_profile_for_user(user)[source]

Returns site-specific profile for this user. Raises ProfileNotConfigured if settings.ACCOUNTS_PROFILE_MODEL is not set, and ImproperlyConfigured if the corresponding model can’t be found.

mezzanine.accounts.get_profile_form()[source]

Returns the profile form defined by settings.ACCOUNTS_PROFILE_FORM_CLASS.

mezzanine.accounts.get_profile_model()[source]

Returns the Mezzanine profile model, defined in settings.ACCOUNTS_PROFILE_MODEL, or None if no profile model is configured.

mezzanine.accounts.get_profile_user_fieldname(profile_model=None, user_model=None)[source]

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)[source]

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', form_class=<class 'mezzanine.accounts.forms.LoginForm'>, extra_context=None)[source]

Login form.

mezzanine.accounts.views.logout(request)[source]

Log the user out.

mezzanine.accounts.views.profile(request, username, template=u'accounts/account_profile.html', extra_context=None)[source]

Display a profile.

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

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)[source]

Profile update form.

mezzanine.accounts.views.signup(request, template=u'accounts/account_signup.html', extra_context=None)[source]

Signup form.

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

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)[source]

Fields for login.

clean()[source]

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

save()[source]

Just return the authenticated user - used for logging in.

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

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

save()[source]

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

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

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

clean_email()[source]

Ensure the email address is not already registered.

clean_password2()[source]

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

clean_username()[source]

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)[source]

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)[source]

Returns the login form:

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

mezzanine.accounts.templatetags.accounts_tags.profile_fields(user)[source]

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)[source]

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)[source]

Returns the signup form:

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

mezzanine.accounts.templatetags.accounts_tags.username_or(user, attr)[source]

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.AbstractBaseField(*args, **kwargs)[source]

A field for a user-built form.

get_choices()[source]

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

is_a(*args)[source]

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

class mezzanine.forms.models.Field(id, _order, label, field_type, required, visible, choices, default, placeholder_text, help_text, form)[source]
exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.forms.models.FieldEntry(*args, **kwargs)[source]

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

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.forms.models.FieldManager[source]

Only show visible fields when displaying actual form..

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

A user-built form.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.forms.models.FormEntry(*args, **kwargs)[source]

An entry submitted via a user-built form.

exception DoesNotExist
exception MultipleObjectsReturned

mezzanine.forms.forms

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

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

columns()[source]

Returns the list of selected column names.

rows(csv=False)[source]

Returns each row based on the selected criteria.

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

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

email_to()[source]

Return the value entered for the first field of type forms.EmailField.

save(**kwargs)[source]

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

mezzanine.forms.page_processors

mezzanine.forms.page_processors.form_processor(request, page)[source]

Display a built form and handle submission.

mezzanine.forms.page_processors.format_value(value)[source]

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

mezzanine.forms.admin

class mezzanine.forms.admin.FieldAdmin(parent_model, admin_site)[source]

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

model

alias of mezzanine.forms.models.Field

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

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)[source]

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

file_view(request, field_entry_id)[source]

Output the file for the requested field entry.

get_urls()[source]

Add the entries view to urls.

mezzanine.galleries

Implements a photo gallery content type.

mezzanine.galleries.models

class mezzanine.galleries.models.BaseGallery(*args, **kwargs)[source]

Base gallery functionality.

save(delete_zip_import=True, *args, **kwargs)[source]

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.Gallery(*args, **kwargs)[source]

Page bucket for gallery photos.

exception DoesNotExist
exception MultipleObjectsReturned
class mezzanine.galleries.models.GalleryImage(id, _order, gallery, file, description)[source]
exception DoesNotExist
exception MultipleObjectsReturned
save(*args, **kwargs)[source]

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[source]

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.

class Placeholder[source]

A Weakly-referable wrapper of object.

clear_cache()[source]

Clear the settings cache for the current request.

use_editable()[source]

Clear the cache for the current request so that editable settings are fetched from the database on next access. Using editable settings is the default, so this is deprecated in favour of clear_cache().

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

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)[source]

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

exception DoesNotExist
exception MultipleObjectsReturned

mezzanine.conf.forms

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

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

format_help(description)[source]

Format the setting’s description into HTML.

save()[source]

Save each of the settings to the DB.

mezzanine.conf.admin

class mezzanine.conf.admin.SettingsAdmin(model, admin_site)[source]

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(settings, allowed_settings, *args, **kwargs)[source]

Dict wrapper for template settings. This exists to enforce the restriction of settings in templates to those named in TEMPLATE_ACCESSIBLE_SETTINGS, and to warn about deprecated settings.

Django’s template system attempts a dict-style index lookup before an attribute lookup when resolving dot notation in template variables, so we use __getitem__() this as the primary way of getting at the settings.

mezzanine.conf.context_processors.settings(request=None)[source]

Add the settings object to the template context.

mezzanine.template

class mezzanine.template.Library[source]

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)[source]

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.

render_tag(tag_func)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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(id, type, value, interested)[source]
exception DoesNotExist
exception MultipleObjectsReturned
run()[source]

Request new tweets from the Twitter API.

class mezzanine.twitter.models.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)[source]
exception DoesNotExist
exception MultipleObjectsReturned
exception mezzanine.twitter.models.TwitterQueryException[source]

mezzanine.twitter.managers

class mezzanine.twitter.managers.TweetManager[source]

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

get_for(query_type, value)[source]

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)[source]

Tweets for the default settings.

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

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)[source]

Tweets for a user’s list.

Tweets for a search query.

mezzanine.twitter.templatetags.twitter_tags.tweets_for_user(parser, token)[source]

Tweets for a user.

mezzanine.twitter.management.commands

class mezzanine.twitter.management.commands.poll_twitter.Command(stdout=None, stderr=None, no_color=False)[source]

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)[source]

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)[source]

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(*args, **kwds)[source]

Returns True if a cache backend is configured, and the cache middleware classes or subclasses thereof are present. This will be evaluated once per run, and then cached.

mezzanine.utils.cache.cache_key_prefix(request)[source]

Cache key for Mezzanine’s cache middleware. Adds the current site ID.

mezzanine.utils.cache.cache_set(key, value, timeout=None, refreshed=False)[source]

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()[source]

Returns the secret token that delimits content wrapped in the nevercache template tag.

class mezzanine.utils.conf.SitesAllowedHosts[source]

This is a fallback for Django’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.middlewares_or_subclasses_installed(needed_middlewares)[source]

When passed an iterable of dotted strings, returns True if all of the middlewares (or their subclasses) are installed.

mezzanine.utils.conf.real_project_name(project_name)[source]

Used to let Mezzanine run from its project template directory, in which case “{{ project_name }}” won’t have been replaced by a real project name.

mezzanine.utils.conf.set_dynamic_settings(s)[source]

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.

Utils called from project_root/docs/conf.py when Sphinx documentation is generated.

mezzanine.utils.docs.build_changelog(docs_path, package_name=u'mezzanine')[source]

Converts Mercurial commits into a changelog in RST format.

mezzanine.utils.docs.build_modelgraph(docs_path, package_name=u'mezzanine')[source]

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')[source]

Updates the requirements file with Mezzanine’s version number.

mezzanine.utils.docs.build_settings_docs(docs_path, prefix=None)[source]

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)[source]

Recursively call force_text on value.

mezzanine.utils.email.send_approve_mail(request, user)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Converts a string containing comma separated email addresses into a list of email addresses.

mezzanine.utils.email.subject_template(template, context)[source]

Loads and renders an email subject template, returning the subject string.

class mezzanine.utils.html.TagCloser(html)[source]

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.absolute_urls(html)[source]

Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be used as a general richtext filter.

mezzanine.utils.html.decode_entities(html)[source]

Remove HTML entities from a string. Adapted from http://effbot.org/zone/re-sub.htm#unescape-html

mezzanine.utils.html.escape(*args, **kwargs)[source]

Escapes HTML according to the rules defined by the settings RICHTEXT_FILTER_LEVEL, RICHTEXT_ALLOWED_TAGS, RICHTEXT_ALLOWED_ATTRIBUTES, RICHTEXT_ALLOWED_STYLES.

mezzanine.utils.html.thumbnails(*args, **kwargs)[source]

Given a HTML string, converts paths in img tags to thumbnail paths, using Mezzanine’s thumbnail template tag. Used as one of the default values in the RICHTEXT_FILTERS setting.

mezzanine.utils.importing.import_dotted_path(path)[source]

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)[source]

Returns the directory path for the given package or module.

class mezzanine.utils.models.AdminThumbMixin[source]

Provides a thumbnail method on models for admin classes to reference in the list_display definition.

class mezzanine.utils.models.ModelMixin[source]

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[source]

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, model)[source]

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()[source]

Returns the app_label.object_name string for the user model.

mezzanine.utils.models.upload_to(field_path, default)[source]

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()[source]

Responsible for determining the current Site instance to use when retrieving data for any SiteRelated models. If we’re inside an override_current_site_id context manager, return the overriding site ID. Otherwise, try to determine the site using the following methods in order:

  • site_id in session. Used in the admin so that admin users can switch sites and stay on the same domain for the admin.
  • The id of the Site object corresponding to the hostname in the current request. This result is cached.
  • MEZZANINE_SITE_ID environment variable, so management commands or anything else outside of a request can specify a site.
  • SITE_ID setting.

If a current request exists and the current site is not overridden, the site ID is stored on the request object to speed up subsequent calls.

mezzanine.utils.sites.has_site_permission(user)[source]

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()[source]

Returns the directory of the theme associated with the given host.

mezzanine.utils.sites.override_current_site_id(*args, **kwds)[source]

Context manager that overrides the current site id for code executed within it. Used to access SiteRelated objects outside the current site.

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

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)[source]

Create multiple levels of recursive objects.

queries_used_for_template(template, **context)[source]

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

setUp()[source]

Creates an admin user, sets up the debug cursor, so that we can track the number of queries used in various places, and creates a request factory for views testing.

tearDown()[source]

Clean up the admin user created and debug cursor.

mezzanine.utils.tests.copy_test_to_media(module, name)[source]

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)[source]

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)[source]

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

mezzanine.utils.timezone.get_best_local_timezone()[source]

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)[source]

Returns the URL for the given model and admin url name.

mezzanine.utils.urls.clean_slashes(path)[source]

Canonicalize path by removing leading slashes and conditionally removing trailing slashes.

mezzanine.utils.urls.home_slug()[source]

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)[source]

Returns the redirect response for login/signup. Favors: - next param - LOGIN_REDIRECT_URL setting - homepage

mezzanine.utils.urls.next_url(request)[source]

Returns URL to redirect to from the next param in the request.

mezzanine.utils.urls.path_to_slug(path)[source]

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)[source]

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

mezzanine.utils.urls.slugify_unicode(s)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.