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.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.
-
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 variousshort_url
mechanics below.Technically we should use
self.site.domain
, here, however if we were to invoke theshort_url
mechanics on a list of data (eg blog post list view), we’d trigger a db query per item. Usingcurrent_request
should provide the same result, since site related data should only be loaded based on the current host anyway.
-
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 useauto_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 theset_short_url_for
template tag andTweetableAdmin
.If no sharing service is defined (bitly is the one implemented, but others could be by overriding
generate_short_url
), theSHORT_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 storeget_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.
-
-
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 withForeignKey("self")
, or with Generic Relations. We may also want this feature for models that aren’t ordered with respect to a particular field.
-
class
mezzanine.core.models.
OrderableBase
[source]¶ Checks for
order_with_respect_to
on the model’s innerMeta
class and if found, copies it to a custom attribute and deletes it since it will cause errors when used withForeignKey("self")
. Also creates theordering
attribute on theMeta
class if not yet provided.
-
class
mezzanine.core.models.
Ownable
(*args, **kwargs)[source]¶ Abstract model that provides ownership of an object for a user.
-
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
¶
-
exception
-
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. Seemezzanine.utils.sites.current_site_id
for implementation details.
-
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.
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 variableMEZZANINE_SITE_ID
(which can be used by management commands with the--site
arg, finally falling back tosettings.SITE_ID
if none of those match a site.
-
class
mezzanine.core.managers.
DisplayableManager
(field_name=None, *args, **kwargs)[source]¶ Manually combines
CurrentSiteManager
,PublishedManager
andSearchableManager
for theDisplayable
model.
-
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.
-
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 tellSearchableQuerySet
which search fields to use. Also used byDisplayableAdmin
to populate Django admin’ssearch_fields
attribute.Search fields can be populated via
SearchableManager.__init__
, which then get stored inSearchableManager._search_fields
, which serves as an approach for defining an explicit set of fields to be used.Alternatively and more commonly,
search_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
orTextField
instances.
-
-
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.
-
-
mezzanine.core.managers.
search_fields_to_dict
(fields)[source]¶ In
SearchableQuerySet
andSearchableManager
, 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 usesTemplateResponse
viamezzanine.utils.views.render
.
-
mezzanine.core.views.
displayable_links_js
(request)[source]¶ 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.
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 usingOrderWidget
.
-
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
andSelectDateWidget
.
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 subclassOrderable
.-
form
¶
-
-
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.
-
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 afieldsets
attribute that excludes theuser
field or simple adduser
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 formatapp_label.object_name
, and allows models subclassingOwnable
to be excluded from filtering, eg: ownership should not imply permission to edit.
-
-
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.
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
isTrue
.If
SSL_FORCE_HOST
isTrue
, 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 ofuser.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.
mezzanine.core.templatetags.mezzanine_tags
¶
Adopted from
django.contrib.admin.sites.AdminSite.index
. Returns a list of lists of models grouped and ordered according tomezzanine.conf.ADMIN_MENU_ORDER
. Called from theadmin_dropdown_menu
template tag as well as theapp_list
dashboard widget.
Renders the app list for the admin dropdown menu navigation.
Renders the app list for the admin dashboard widget.
Dummy tag for fallback when django-compressor isn’t installed.
Takes an index for retrieving the sequence of template tags from
mezzanine.conf.DASHBOARD_TAGS
to render into the admin dashboard.
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 returnsTrue
, or the logged in user has change permissions for the model.
Set up the required JS/CSS for the in-line editing toolbar and controls.
Renders an alert if the form has any errors.
Renders fields for a form with an optional template choice.
Return the full URL for a Gravatar given an email hash.
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.
Returns
True
if the given app name is in theINSTALLED_APPS
setting.
Remove HTML tags, entities and superfluous characters from meta blocks.
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.
Renders the recent actions list for the admin dashboard widget.
Takes a value edited via the WYSIWYG editor, and passes it through each of the functions specified by the RICHTEXT_FILTERS setting.
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 stringall
can also be used, in which case the models defined by theSEARCH_MODEL_CHOICES
setting will be used.
Sets the
short_url
attribute of the given model for share links in the template.
General sort filter - sorts by either attribute or key.
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.
Translates the current URL for the given language code, eg:
{% translate_url “de” %}
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
¶
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 onPage
, a concrete model, then eachPage
subclass loses the custom manager.
-
class
mezzanine.pages.models.
Link
(*args, **kwargs)[source]¶ A general content type for creating external links in the page menu.
-
exception
DoesNotExist
¶
-
exception
MultipleObjectsReturned
¶
-
exception
-
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_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 aPageMoveException
with a single argument (message explaining the reason).
-
description_from_content
()[source]¶ Override
Displayable.description_from_content
to load the content type subclass for whensave
is called directly on aPage
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 viaPage.objects.with_ascendants_for_slug
.
-
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.
-
exception
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 viamezzanine.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 ofPage
. Handles redirections between admin interfaces for thePage
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 theADD_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.
-
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.
mezzanine.pages.templatetags.pages_tags
¶
Create a select list containing each of the models that subclass the
Page
model.
Return a list of child pages for the given parent, storing all pages in a dict in the context when first called using parents as keys for retrieval on subsequent recursive calls from the menu template.
Assigns a permissions dict to the given model, much like Django does with its dashboard app list.
Used within the change list for pages, to implement permission checks for the navigation tree.
Assigns a permissions dict to the given page instance, combining Django’s permission for the page’s model and a permission check against the instance itself calling the page’s
can_add
,can_change
andcan_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 theprocessor_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 theexact_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
¶
-
exception
-
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
¶
-
exception
-
class
mezzanine.generic.models.
Rating
(*args, **kwargs)[source]¶ A rating that can be given to a piece of content.
-
exception
DoesNotExist
¶
-
exception
MultipleObjectsReturned
¶
-
exception
-
class
mezzanine.generic.models.
ThreadedComment
(*args, **kwargs)[source]¶ Extend the
Comment
model fromdjango_comments
to add comment threading.Comment
provides its own site foreign key, so we can’t inherit fromSiteRelated
inmezzanine.core
, and therefore need to set the site onsave
.CommentManager
inherits from Mezzanine’sCurrentSiteManager
, so everything else site related is already provided.-
exception
DoesNotExist
¶
-
exception
MultipleObjectsReturned
¶
-
exception
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 toFalse
.
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 adefault_related_model
attribute which can be defined on subclasses as a default for theto
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 callingrelated_items_changed
.
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
- Add a consistent default value for
-
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.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 theKEYWORDS_FIELD_string
field insearch_fields
.
-
formfield
(**kwargs)[source]¶ Provide the custom form widget for the admin, since there isn’t a form field mapped to
GenericRelation
model fields.
Stores the keywords as a single string for searching.
-
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 isTrue
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 thenext
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.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 eachKeyword
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 withKeyword
ids and fetches the sequence ofAssignedKeyword
-
-
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.
mezzanine.generic.admin
¶
mezzanine.generic.templatetags.comment_tags
¶
Passed comment text to be rendered through the function defined by the
COMMENT_FILTER
setting. If no function is defined (the default), Django’slinebreaksbr
andurlize
filters are used.
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.
Provides a generic context variable name for the object that comments are being rendered for.
Dashboard widget for displaying recent comments.
mezzanine.generic.templatetags.disqus_tags
¶
Returns a unique identifier for the object to be used in DISQUS JavaScript.
Provides a generic context variable which adds single-sign-on support to DISQUS if
COMMENTS_DISQUS_API_PUBLIC_KEY
andCOMMENTS_DISQUS_API_SECRET_KEY
are specified.
mezzanine.generic.templatetags.keyword_tags
¶
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 aweight
attribute that can be used to create a tag cloud.
mezzanine.generic.templatetags.rating_tags
¶
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
¶
-
exception
-
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 valueyear
,month
, orday
. Each of these maps to the name of the corresponding urlpattern, and if defined, we loop through each of these and build up the kwargs for the correct urlpattern. The order which we loop through them is important, since the order goes from least granular (just year) to most granular (year/month/day).
-
exception
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
whereXXX
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
whereXXX
is either the category slug or author’s username if given.
mezzanine.blog.forms
¶
mezzanine.blog.admin
¶
mezzanine.blog.feeds
¶
mezzanine.blog.templatetags.blog_tags
¶
Put a list of authors (users) for blog posts into the template context.
Put a list of categories for blog posts into the template context.
Put a list of dates for blog posts into the template context.
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 %}
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
andcontent
are strings for the post.old_url
is a string that a redirect will be created for.pub_date
is assumed to be adatetime
object.tags
andcategories
are sequences of strings.comments
is a sequence of dicts - each dict should be the return value ofadd_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
-
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.
-
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.
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.
-
mezzanine.accounts.
get_profile_for_user
(user)[source]¶ Returns site-specific profile for this user. Raises
ProfileNotConfigured
ifsettings.ACCOUNTS_PROFILE_MODEL
is not set, andImproperlyConfigured
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
, orNone
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.
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.
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 toTrue
. 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.
-
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.
-
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_password2
()[source]¶ Ensure the password fields are equal, and match the minimum length defined by
ACCOUNTS_MIN_PASSWORD_LENGTH
.
-
mezzanine.accounts.templatetags.accounts_tags
¶
Returns the login form:
{% login_form as form %} {{ form }}
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 toTrue
, and also in the account approval emails sent to administrators when theACCOUNTS_APPROVAL_REQUIRED
setting is set toTrue
.
Returns the profile form for a user:
{% if request.user.is_authenticated %} {% profile_form request.user as form %} {{ form }} {% endif %}
Returns the signup form:
{% signup_form as form %} {{ form }}
Returns the user’s username for display, or an alternate attribute if
ACCOUNTS_NO_USERNAME
is set toTrue
.
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.
-
class
mezzanine.forms.models.
Field
(id, _order, label, field_type, required, visible, choices, default, placeholder_text, help_text, form)[source]¶ -
exception
DoesNotExist
¶
-
exception
MultipleObjectsReturned
¶
-
exception
-
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
¶
-
exception
-
class
mezzanine.forms.models.
FieldManager
[source]¶ Only show visible fields when displaying actual form..
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.
mezzanine.forms.page_processors
¶
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.
mezzanine.galleries
¶
Implements a photo gallery content type.
mezzanine.galleries.models
¶
mezzanine.galleries.admin
¶
mezzanine.conf
¶
Drop-in replacement for django.conf.settings
that provides a
consistent access method for settings defined in applications, the project
or Django itself. Settings can also be made editable via the admin.
-
class
mezzanine.conf.
Settings
[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.
-
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
¶
mezzanine.conf.forms
¶
mezzanine.conf.admin
¶
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.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 tovar_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 untilendmytag
. The decorated func’s return value is used to render the parsed content and takes three arguments - the parsed content between the start and end tags, the template context and the tag token.
-
mezzanine.template.loader_tags
¶
Allows the template
foo/bar.html
to extendfoo/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
andfilesystem
) 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
, andcached
loaders are supported. Theeggs
loader, and any loader that implementsload_template_source
with a source string returned, should also theoretically work.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.
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.
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
¶
-
exception
mezzanine.twitter.managers
¶
mezzanine.twitter.templatetags.twitter_tags
¶
Tweets for the default settings.
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.
Tweets for a user’s list.
Tweets for a search query.
Tweets for a user.
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 hasCACHE_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.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 theACCOUNTS_APPROVAL_REQUIRED
setting isTrue
.
-
mezzanine.utils.email.
send_approved_mail
(request, user)[source]¶ Sends an email to a user once their
is_active
status goes fromFalse
toTrue
when theACCOUNTS_APPROVAL_REQUIRED
setting isTrue
.
-
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. Theverification_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 theRICHTEXT_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 amixin_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
andOrderable
abstract models to access thePage
instance when instances of custom content types, (eg: models that inherit fromPage
) need to query thePage
model to determine correct values forslug
and_order
which are only relevant in the context of thePage
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 theUPLOAD_TO_HANDLERS
setting.
-
mezzanine.utils.sites.
current_site_id
()[source]¶ Responsible for determining the current
Site
instance to use when retrieving data for anySiteRelated
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 thehas_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 anis_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.
-
-
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 theurl
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 aPage
instance’s slug.
-
mezzanine.utils.urls.
slugify
(s)[source]¶ Loads the callable defined by the
SLUGIFY
setting, which defaults to theslugify_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 customeditable
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 theSPAM_FILTERS
setting.
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 theSPAM_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 frommax_paging_links
.
-
mezzanine.utils.views.
render
(request, templates, dictionary=None, context_instance=None, **kwargs)[source]¶ Mimics
django.shortcuts.render
but uses a TemplateResponse formezzanine.core.middleware.TemplateForDeviceMiddleware
Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded.