.. _topics-modules:

===============
Library Modules
===============

.. admonition:: About this document

   This document describes the functionality provided by the various python
   modules in Softwarefabrica Django Utils.

.. contents::
   :depth: 3

Modules
=======

``usearch``
-----------

The ``usearch`` module implements the search technique described in `Adding
search to a Django site in a snap`_.

``get_query``
~~~~~~~~~~~~~

The ``get_query`` function builds and returns a composite query object (see the
`Q object`_ documentation), using the provided search fields and query
string. The query string, typically coming from a form, contains the search
terms. The search fields are the model field names that are to be searched.
The resultant `Q object` can then be applied to filter results in a normal
Django query.

Example usage::

    def v_search(request, template_name='wiki/search_results.html'):
        from softwarefabrica.django.utils import usearch
        
        query_string = ''
        found_pagecontents = None
        if ('q' in request.GET) and request.GET['q'].strip():
            query_string = request.GET['q']

            pagecontent_query = usearch.get_query(query_string, ['title', 'text',
                                                                'page__name', 'page__desc',])
        
            found_pagecontents = PageContent.objects.filter(pagecontent_query).order_by('-page', '-created', '-rev')

        return render_to_response(request, template_name,
                                  { 'query_string': query_string,
                                    'pagecontents': found_pagecontents,
                                    })


.. _`Adding search to a Django site in a snap`: http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/
.. _`Q object`: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

``viewshelpers``
----------------

The ``viewshelpers`` module provides various useful functions.

``context_vars``
~~~~~~~~~~~~~~~~

This function can be used as a `template context processor`_ to automatically
populate template contexts with some variables from the project `settings`_
(this requires the use of a `RequestContext`_, see below the
``render_to_response`` convenience function on how to do it effortlessly).

To use this context processor, it's necessary to add
``'softwarefabrica.django.utils.viewshelpers.context_vars'`` to
``TEMPLATE_CONTEXT_PROCESSORS`` in your `settings`_ file::

    TEMPLATE_CONTEXT_PROCESSORS = (
        ...
        'softwarefabrica.django.utils.viewshelpers.context_vars',
    )

The variables pushed into the context are:

``basesite``
    value of ``Site.objects.get_current()`` when using the `"sites" framework`_,
    None otherwise.

``domain``
    the domain part of the ``Site`` when using the `"sites" framework`_,
    the empty string otherwise.

``static``
    the value of ``static_media_prefix()``, which is
    ``settings.STATIC_MEDIA_PREFIX`` if defined, or in second instance
    ``settings.STATIC_URL``, or finally ``"/static"`` (always with the trailing
    slash removed).

``upload``
    value of ``settings.MEDIA_URL``

``admin``
    value of ``settings.ADMIN_MEDIA_PREFIX``

``images``
    same as ``static`` with a ``"/images"`` suffix

``js``
    same as ``static`` with a ``"/js"`` suffix

.. _`settings`: http://docs.djangoproject.com/en/dev/topics/settings/
.. _`template context processor`: http://docs.djangoproject.com/en/dev/ref/settings/#setting-TEMPLATE_CONTEXT_PROCESSORS
.. _`"sites" framework`: http://docs.djangoproject.com/en/dev/ref/contrib/sites/?from=olddocs
.. _`RequestContext`: http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs

``render_to_response``
~~~~~~~~~~~~~~~~~~~~~~

An extension of the Django shortcut function `render_to_response`_, which passes
a `RequestContext`_ to the template instead of a simple `Context`. This has the
effect of forcing execution of the `context processors`_, which put
additional variables into the template context. This function is especially
convenient when using the aforementioned ``context_vars`` context processor.

``softwarefabrica.django.utils.viewshelpers.render_to_response`` renders a given
template with a `RequestContext`_ built from the given context dictionary and
request object, and returns an ``HttpResponse`` object with that rendered text.

Required arguments
^^^^^^^^^^^^^^^^^^

``request``
    The `HttpRequest`_ object to use.

``template``
    The full name of a template to use.

Optional arguments
^^^^^^^^^^^^^^^^^^

``dictionary``
    A dictionary of values to add to the template context. By default, this
    is an empty dictionary. If a value in the dictionary is callable, the
    view will call it just before rendering the template.

``context_instance``
    The context instance to render the template with, when specified. If this
    parameter is not passed, or is ``None``, a `RequestContext`_ built
    from the ``request`` will be used instead.

``mimetype``
    The MIME type to use for the resulting document. Defaults to the value of
    the ``DEFAULT_CONTENT_TYPE`` setting.

Example
^^^^^^^

The following example renders the template ``myapp/index.html`` with the
MIME type ``application/xhtml+xml``::

    from softwarefabrica.django.utils.viewshelpers import render_to_response

    def my_view(request):
        # View code here...
        return render_to_response(request, 'myapp/index.html', {"foo": "bar"},
            mimetype="application/xhtml+xml")

This example is equivalent to::

    from django.http import HttpResponse
    from django.template import Context, loader

    def my_view(request):
        # View code here...
        t = loader.get_template('myapp/template.html')
        c = RequestContext(request, {'foo': 'bar'})
        r = HttpResponse(t.render(c),
            mimetype="application/xhtml+xml")

.. _`render_to_response`: http://docs.djangoproject.com/en/dev/topics/http/shortcuts/?from=olddocs
.. _`RequestContext`: http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs
.. _`context processors`: http://docs.djangoproject.com/en/dev/ref/settings/#setting-TEMPLATE_CONTEXT_PROCESSORS
.. _`HttpRequest`: http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest

``managers``
------------

The ``managers`` module provids generic custom model managers.

``QuerySetManager``
~~~~~~~~~~~~~~~~~~~

The ``QuerySetManager`` is the generic model manager described in
`jQuery style chaining with the Django ORM`_.

.. _`jQuery style chaining with the Django ORM`: http://simonwillison.net/2008/May/1/orm/
