Below are auto-generated docs mostly covering each of the packages contained within Mezzanine that are added to settings.INSTALLED_APPS.
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.
Provides abstract models and admin features used throughout the various Mezzanine apps.
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.
Returns a new short URL generated using bit.ly if credentials for the service have been specified.
Raise an error if called on a subclass without get_absolute_url defined, to ensure all search results contains a URL.
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.
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.
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.
Abstract model that provides meta data for content.
Returns the first block or sentence of the first content-like field.
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.
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.
Abstract model that provides ownership of an object for a user.
Provides a Rich Text field for managing general content and making it searchable.
Permission relationship between a user and a site that’s used instead of User.is_staff, for admin and inline-editing access.
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.
Abstract model that handles auto-generating slugs. Each slugged object is also affiliated with a specific site object.
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.
Manually combines CurrentSiteManager, PublishedManager and SearchableManager for the Displayable model.
Provides filter for restricting items returned by status and publish date when the given user is not a staff member.
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.
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.
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.
QuerySet providing main search functionality for SearchableManager.
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.
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}
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.
Mimics Django’s 404 handler but with a different template path.
Display search results. Takes an optional “contenttype” GET parameter in the form “app-name.ModelName” to limit search results to a single model.
Mimics Django’s error handler but adds STATIC_URL to the context.
Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile).
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.
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.
Wraps render with a CSS class for styling.
Form for DynamicInlineAdmin that can be collapsed and sorted with drag and drop using OrderWidget.
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.
Add up and down arrows for ordering controls next to a hidden form field.
Combines Django’s SelectDateTimeWidget and SelectDateWidget.
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.
alias of DynamicInlineAdminForm
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.
Admin class for subclasses of the abstract Displayable model.
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',)
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.
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn’t.
If only the singleton instance exists, pass True for singleton into the template which will use CSS to hide the “save and add another” button.
Checks for a POST from the admin login view and if authentication is successful and the “site” interface is selected, redirect to the site.
Request phase for Mezzanine cache middleware. Return a response from cache if found, othwerwise mark the request for updating the cache in UpdateCacheMiddleware.
Port of Django’s RedirectFallbackMiddleware that uses Mezzanine’s approach for determining the current site.
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.
Marks the current user with a has_site_permission which is used in place of user.is_staff to achieve per-site staff access.
Inserts device-specific templates to the template list.
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.
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 returns True, 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 the INSTALLED_APPS setting.
Remove HTML tags, entities and superfluous characters from meta blocks.
Dummy fallback nevercache for when caching is not configured.
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.
Deprecated version of richtext_filters above.
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 string all can also be used, in which case the models defined by the SEARCH_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.
Provides the main structure of a Mezzanine site with a hierarchical tree of pages, each subclassing the Page model to create a content structure.
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.
A page in the page tree. This is the base class that custom content types need to subclass.
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).
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.
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.
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.
Provies a generic method of retrieving the instance of the custom content type’s model for this page.
Subclasses can implement this to provide a template to use in mezzanine.pages.views.page.
Returns True if the page’s slug has an explicitly defined urlpattern and is therefore considered to be overridden.
Create the titles field using the titles up the parent chain and set the initial value for ordering.
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.
Updates the ordering of pages via AJAX from within the admin.
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.
Admin class for the Page model and all subclasses of Page. Handles redirections between admin interfaces for the Page model and its subclasses.
For the Page model, redirect to the add view for the first page model, based on the ADD_PAGE_ORDER setting.
For the Page model, check page.get_content_model() for a subclass and redirect to its admin change view. Also enforce custom change permissions for the page instance.
Redirect to the Page changelist view for Page subclasses.
Enforce custom delete permissions for the page instance.
Return all Page subclasses that are admin registered, ordered based on the ADD_PAGE_ORDER setting.
Hide subclasses from the admin menu.
Enforce page permissions and maintain the parent ID in the querystring.
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.
Used in mezzanine.pages.views.page to ensure PageMiddleware or a subclass has been installed. We cache the result on the PageMiddleware._installed to only run this once. Short path is to just check for the dotted path to PageMiddleware in MIDDLEWARE_CLASSES - if not found, we need to load each middleware class to match a subclass.
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 and can_delete custom methods.
Used within the change list for pages, to implement permission checks for the navigation tree.
Taken from django.contrib.admin.autodiscover and used to run any calls to the processor_for decorator.
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.
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.
A Keyword assigned to a model instance.
Keywords/tags which are managed via a custom JavaScript based widget in the admin.
A rating that can be given to a piece of content.
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.
Provides filter for restricting comments that are not approved if COMMENTS_UNAPPROVED_VISIBLE is set to False.
Extends GenericRelation to:
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.
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.
Returns the value of this field in the given model instance. Needed for Django 1.7: https://code.djangoproject.com/ticket/22552
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.
Stores the keywords as a single string into the KEYWORDS_FIELD_NAME_string field for convenient access when searching.
Swap out any reference to KeywordsField with the KEYWORDS_FIELD_string field in search_fields.
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.
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.
Handle a ThreadedCommentForm submission and redirect back to its related object.
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.
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.
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.
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.
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.
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 and COMMENTS_DISQUS_API_SECRET_KEY are specified.
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.
Provides a generic context variable name for the object that ratings are being rendered for, and the rating form.
Provides a blogging app with posts, keywords, categories and comments. Posts can be listed by month, keyword, category or author.
A category for grouping blog posts into a series.
A blog post.
URLs for blog posts can either be just their slug, or prefixed with a portion of the post’s publish date, controlled by the setting BLOG_URLS_DATE_FORMAT, which can contain the value year, month, or day. Each of these maps to the name of the corresponding urlpattern, and if defined, we loop through each of these and build up the kwargs for the correct urlpattern. The order which we loop through them is important, since the order goes from least granualr (just year) to most granular (year/month/day).
. Custom templates are checked for using the name blog/blog_post_detail_XXX.html where XXX is the blog posts’s slug.
Blog posts feeds - maps format to the correct feed view.
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.
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.
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.
Adds a comment to the post provided.
Adds tags and a redirect for the given obj, which is a blog post or a page.
Adds a page to the list of pages to be imported - used by the Wordpress importer.
Adds a post to the post list for processing.
Processes the converted data into the Mezzanine database correctly.
Import an RSS feed into the blog app.
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.
Implements a Wordpress importer. Takes a file path or a URL for the Wordpress Extended RSS file.
Provides features for non-staff user accounts, such as login, signup with optional email verification, password reset, and integration with user profiles models defined by the AUTH_PROFILE_MODULE setting. Some utility functions for probing the profile model are included below.
Returns site-specific profile for this user. Raises ProfileNotConfigured if settings.AUTH_PROFILE_MODULE is not set, and ImproperlyConfigured if the corresponding model can’t be found.
Returns the profile form defined by settings.ACCOUNTS_PROFILE_FORM_CLASS.
Returns the Mezzanine profile model, defined in settings.AUTH_PROFILE_MODULE, or None if no profile model is configured.
Returns the name of the first field on the profile model that points to the auth.User model.
Just gives the URL prefix for accounts an action - redirect to the profile update form.
Login form.
Catches and redirects any unmatched account URLs to their correct version (account/ to accounts/) as per #934. The URL is constructed manually, handling slashes as appropriate.
Display a profile.
Just gives the URL prefix for profiles an action - redirect to the logged in user’s profile.
Signup form.
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.
Fields for login.
Validates the user’s username or email for sending a login token for authenticating to change their password.
ModelForm for auth.User - used for signup and profile update. If a Profile model is defined via AUTH_PROFILE_MODULE, its fields are injected into the form.
Ensure the password fields are equal, and match the minimum length defined by ACCOUNTS_MIN_PASSWORD_LENGTH.
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 to True, and also in the account approval emails sent to administrators when the ACCOUNTS_APPROVAL_REQUIRED setting is set to True.
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 to True.
A port of django-forms-builder for Mezzanine. Allows admin users to create their own HTML5 forms and export form submissions as CSV.
A field for a user-built form.
A single field value for a form entry submitted via a user-built form.
Form with a set of fields dynamically assigned that can be used to filter entries for the given forms.models.Form instance.
Admin class for the form field. Inherits from TabularDynamicInlineAdmin to add dynamic “Add another” link and drag/drop ordering.
alias of Field
Admin class for the Form model. Includes the urls & views for exporting form entries as CSV and downloading files uploaded via the forms app.
Implements a photo gallery content type.
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.
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.
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.
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.
Extends django.template.Library providing several shortcuts that attempt to take the leg-work out of creating different types of template tags.
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.
Replacement for Django’s inclusion_tag which looks up device specific templates at render time.
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.
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.
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.
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.
Provides models and utilities for displaying different types of Twitter feeds.
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.
Various utility functions used throughout the different Mezzanine apps.
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.
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.
Returns True if a cache backend is configured, and the cache middlware classes are present.
Cache key for Mezzanine’s cache middleware. Adds the current device and site ID.
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.
Returns the secret token that delimits content wrapped in the nevercache template tag.
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.
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.
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.
Determine’s the device name from the request by first looking for an overridding cookie, and if not found then matching the user agent. Used at both the template level for choosing the template to load and also at the cache level as a cache key prefix.
Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted before it’s associate default in the list.
Utils called from project_root/docs/conf.py when Sphinx documentation is generated.
Converts Mercurial commits into a changelog in RST format.
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
Updates the requirements file with Mezzanine’s version number.
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.
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.
Sends an email to a user once their is_active status goes from False to True when the ACCOUNTS_APPROVAL_REQUIRED setting is True.
Send email rendering text and html versions for the specified template name using the context dictionary passed in.
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.
Converts a string containing comma separated email addresses into a list of email addresses.
Loads and renders an email subject template, returning the subject string.
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.
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.
Remove HTML entities from a string. Adapted from http://effbot.org/zone/re-sub.htm#unescape-html
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.
Takes a dotted path to a member name in a module, and returns the member after importing it.
Returns the directory path for the given package or module.
Provides a thumbnail method on models for admin classes to reference in the list_display definition.
This class connects itself to Django’s class_prepared signal. Pass a function and a model or model name to its add() method, and the function will be called with the model as its only parameter once the model has been loaded. If the model is already loaded, the function is called immediately.
Adapted from django.db.models.fields.related and used in mezzanine.generic.fields.
The function passed to this method should accept n arguments, where n=len(models_or_names). When all the models are ready, the function will be called with the models as arguments, in the order they appear in this argument list.
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.
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.
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.
Returns the app_label.object_name string for the user model.
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.
Responsible for determining the current Site instance to use when retrieving data for any SiteRelated models. If a request is available, and the site can be determined from it, we store the site against the request for subsequent retrievals. Otherwise the order of checks is as follows:
- site_id in session. Used in the admin so that admin users can switch sites and stay on the same domain for the admin.
- host for the current request matched to the domain of the site instance.
- MEZZANINE_SITE_ID environment variable, so management commands or anything else outside of a request can specify a site.
- SITE_ID setting.
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.
Returns the directory of the theme associated with the given host.
Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted into the front of the list.
This is the base test case providing common features for all tests across the different apps in Mezzanine.
Create multiple levels of recursive objects.
Return the number of queries used when rendering a template string.
Copies a file from Mezzanine’s test data path to MEDIA_ROOT. Used in tests and demo fixtures.
If pep8 is installed, run it across the given package name returning any warnings or errors found.
If pyflakes is installed, run it across the given package name returning any warnings found.
Compares local timezone offset to pytz’s timezone db, to determine a matching timezone name to use when TIME_ZONE is not set.
Returns the URL for the given model and admin url name.
Canonicalize path by removing leading slashes and conditionally removing trailing slashes.
Returns the slug arg defined for the home urlpattern, which is the definitive source of the url field defined for an editable homepage object.
Returns the redirect response for login/signup. Favors: - next param - LOGIN_REDIRECT_URL setting - homepage
Returns URL to redirect to from the next param in the request.
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.
Loads the callable defined by the SLUGIFY setting, which defaults to the slugify_unicode function.
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/
Ensures a slug is unique for the given queryset, appending an integer to its end until the slug is unique.
Returns ip address for request - first checks HTTP_X_FORWARDED_FOR header, since app will generally be behind a public web server.
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.
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.
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:
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.
Return a paginated page for the given objects, giving it a custom visible_page_range attribute calculated from max_paging_links.
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.