Library Modules

About this document

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

Contents

See also the documentation index.

Modules

crud

The crud module provides all the generic views.

There are two sets: one of Object Oriented views, and one of classic functional views.

The idea for Object Oriented views came from the snippet 1009 on djangosnippets.org.

Object oriented views are made callables by virtue of their special method __call__, and as such they are seen as normal Django views.

The philosophy behind Object Oriented views is to distribute as much as possible their functionality in separate methods, thus allowing the developer to customize the view behaviour by just creating a derived class in which it's necessary to override just the bit it needs to be different. This allows a great flexibility with code that is very compact and easy to understand. The views have methods to fetch the template, preparing its context, preparing a response, populating its headers, and so on.

View

This is the base class for all Object Oriented views. It can be used also as a base for custom "non-generic" Object Oriented views.

All Object Oriented generic views provide the special method __call__, which turns them into callable objects, thus acting as a normal function. Many parameters to the __call__ method - the view parameters - are replicated in the class constructor. This allows to provide once for all a sensible default when instantiating the view object. When the actual view call will take place, any such parameter passed again to the view (the __call__ method), will take precedence over the default passed to the constructor. In the following description we'll document these parameters only once, for the constructor, just listing them for the __call__ method, since their meaning is the same.

__init__ - constructor

Optional arguments
template_name
Name of the template to use, or a list of template names (if a list is specified, the first template found is utilized).
template_loader
Template loader to use (defaults to django.template.loader).
extra_context
Dictionary of items and/or callables to add to template context.
login_required
True if login is required by this view (defaults to False).
context_processors
Context processors passed to RequestContext() (defaults to None).

__call__ - view method

Handles the view, called by Django URL dispatch mechanism.

The flow is the following:

  1. if login is required by the view (login_required is True), and the user is not authenticated, the view return the result of the redirect_to_login method.
  2. view call specific extra context is added to the instance extra context through a call to the apply_extra_context. method.
  3. a template context is generated through a call to get_context
  4. previously constructed extra context is added to the template context by a call to apply_extra_context.
  5. the append_to_context method is called to perform any additional manipulations of the template context. This method does nothing, but is provided to be overridden in derived classes.
  6. the template is fetched by the get_template method
  7. an HttpResponse is generated by the get_response method and returned by the view.

Any such point can be customized in derived classes by overriding the corresponding method. The flow itself can be customized by overriding the __call__ method.

Required arguments
request
The HttpRequest object.
Optional arguments

template_name

template_loader

extra_context

login_required

context_processors

redirect_to_login

By default it calls django.contrib.auth.views.redirect_to_login passing request.path.

apply_extra_context

Adds to context the extra context passed as argument, or the instance extra context if the former is not specified. The extra context is added using the merge_dict method.

Optional arguments

extra_context

get_context

Builds a RequestContext using the data passed in dictionary, and using the passed context_processors, or the instance context_processors if the former is not specified.

Required arguments
request
The HttpRequest object.
Optional arguments
dictionary
Dictionary to use in building the context, Defaults to the empty dictionary.
context_processors
List of context processors. Defaults to None.

append_to_context

By default it does nothing, but can be customized in derived classes to further manipulate the context.

Required arguments
context
The RequestContext object.
request
The HttpRequest object.

get_template

Fetches the template to use.

Optional arguments
template_name
Name of the template to use, or a list of template names (if a list is specified, the first template found is utilized). Defaults to None. If it's not specified, the instance template_name is used.
template_loader
Template loader to use. Defaults to None. If it's note specified, the instance template_loader is used (which defaults to django.template.loader).

get_response

Returns an HttpResponse object based on given template, context and MIME type.

Required arguments
template
The template object to use.
context_instance
The template context to use.
Optional arguments
mimetype
MIME type to use. Defaults to None, in which case the HttpResponse object is built without specifying the MIME type.

populate_xheaders

Adds the X-Object-Type and X-Object-Id headers to the given HttpResponse according to the given model and object_id -- but only if the given HttpRequest object has an IP address within the INTERNAL_IPS setting or if the request is from a logged in staff member.

It's a wrapper method for django.core.xheaders.populate_xheaders. Can be customized in derived classes to provide additional headers.

It's not called in the base View class. Call it explicitly in derived __call__ methods.

Required arguments
request
The HttpRequest object.
response
The HttpResponse object.
model
Instance model.
object_id
Instance id.

merge_dict

Adds items from added_dict dict to the given target_dict dict, calling any callables in added_dict. Returns the updated target_dict dict.

Required arguments
target_dict
Dictionary to update.
added_dict
Dictionary to add.

GenericView

An abstract base class for implementing an Object Oriented generic view. This class contains some basic functionality for handling a form, even if a generic views doesn't necessarily use forms. This functionality is provided here to factor it for all derived classes that could need it.

Derives from View.

__init__ - constructor

Optional arguments
model
Django model class to handle with the generic view. One of model or form_class is required.
form_class
ModelForm subclass to use. One of form_class or model is required.
template_name
Name of the template to use, or a list of template names (if a list is specified, the first template found is utilized).
template_loader
Template loader to use (defaults to django.template.loader).
extra_context
Dictionary of items and/or callables to add to template context.
login_required
True if login is required by this view (defaults to False).
context_processors
Context processors passed to RequestContext() (defaults to None).
fields
Passed as the fields parameter to softwarefabrica.django.forms.extended.modelform_factory.
exclude
Passed as the exclude parameter to softwarefabrica.django.forms.extended.modelform_factory.
fieldorder
If specified, it's passed to the form class when instantiating the form.
formfield_callback
If specified, it's passed as the formfield_callback parameter to softwarefabrica.django.forms.extended.modelform_factory.
formbase
Passed as the form parameter to softwarefabrica.django.forms.extended.modelform_factory. Defaults to softwarefabrica.django.forms.extended.ModelForm.

__call__ - view method

Required arguments
request
The HttpRequest object.
Optional arguments

model

form_class

template_name

template_loader

extra_context

login_required

context_processors

fields

exclude

fieldorder

formfield_callback

formbase

append_to_context

Adds some additional variables to the template context. The variables added are:

is_popup
True if the view is a popup. Determined from the request GET _popup variable.
model
Django model class. From the model parameter.
meta
Model meta data, equal to model._meta.
verbose_name
Model verbose name, equal to model._meta.verbose_name
object_name
Model object name, equal to model._meta.object_name.lower()
template_object_name
Equal to obj. Added only if obj is not None.
template_object_name + _id
Equal to obj primary key. Added only if obj is not None.
Required arguments
context
The RequestContext object.
request
The HttpRequest object.
model
Django model class.
Optional arguments
obj
Django model instance. Defaults to None.
template_object_name
Template context variable name for the object instance. Defaults to object.

get_template

Fetches the template to use. If template_name is not specified, it uses the following list:

  1. APP_LABEL / MODEL_NAME _form.html
  2. APP_LABEL / object_form.html
  3. MODEL_NAME _form.html
  4. object_form.html
Optional arguments
model
Django model class.
template_name
Name of the template to use, or a list of template names (if a list is specified, the first template found is utilized). Defaults to None. If it's not specified, the instance template_name is used.
template_loader
Template loader to use. Defaults to None. If it's note specified, the instance template_loader is used (which defaults to django.template.loader).

get_model_and_form_class

Returns a model and form class based on the model and form_class parameters that were passed to the generic view.

If form_class is given then its associated model will be returned along with form_class itself. Otherwise, if model is given, model itself will be returned along with a softwarefabrica.django.forms.extended.ModelForm class created from model.

form is the form base class used (passed to ModelFormMetaclass to create the final form class).

Optional arguments
model
Django model class.
form_class
ModelForm subclass to use. One of form_class or model is required. If form_class is specified, then its associated model will be returned along with form_class itself. Otherwise, if model is given, model itself will be returned along with a softwarefabrica.django.forms.extended.ModelForm class created from model.
fields
Passed as the fields parameter to softwarefabrica.django.forms.extended.modelform_factory.
exclude
Passed as the exclude parameter to softwarefabrica.django.forms.extended.modelform_factory.
formfield_callback
If specified, it's passed as the formfield_callback parameter to softwarefabrica.django.forms.extended.modelform_factory.
form
Passed as the form parameter to softwarefabrica.django.forms.extended.modelform_factory (and in turn to ModelFormMetaclass). Defaults to softwarefabrica.django.forms.extended.ModelForm.
popup_models
a list of Django db model classes for which popup widgets should be used, when referenced by ForeignKey or ManyToManyField fields. If not specified, all model classes are candidates for the new widgets. Keep in mind that to actually use the extended widgets, the models must implement the proper "protocol" (a set of methods used by the widgets, see the relevant softwarefabrica.django.forms documentation for more information).

get_form_kwargs

Returns a dictionary of arguments to construct the appropriate form_class instance. By default it passes the data and files arguments built respectively from request.POST and request.FILES.

Required arguments
request
The HttpRequest object.

get_form

Return the appropriate form_class instance based on the request.

Required arguments
request
The HttpRequest object.
Optional arguments
form_class
Form class to build the form with. Defaults to the instance form class.
fieldorder
fieldorder parameter passed to the form class, if specified. Defaults to the instance fieldorder.
initial
initial parameter passed to the form class, if specified.

save_instance

Saves a model instance into the database.

Required arguments
obj
Model instance to save.
Optional arguments
form
Form instance. If specified it's used to save the related many-to-many associations, with the save_m2m method.

save_m2m

Saves many-to-many relations associated to a form.

Required arguments
form
Form instance containing many-to-many relations.

delete_instance

Delete a model instance from the database.

Required arguments
obj
Model instance to delete.

save_form

Saves a form associated instance. It's code is:

return self.save_instance(form.save(commit=False), form)
Required arguments
form
Form instance.

CreateObjectView

Generic Object Oriented object-creation view.

Derives from GenericView.

Constructor arguments

same as in GenericView, and additionally:

post_save_redirect
URL to redirect to after successful object save. post_save_redirect should be a string, and can contain named string- substitution place holders of the object instance field names. If post_save_redirect is None or an empty string, the default is to send to the URL returned by the instance get_absolute_url(). If the object has no get_absolute_url method, an ImproperlyConfigured exception is raised.
popup_models
Same as in GenericView

View call arguments

same as in GenericView, and additionally:

post_save_redirect
Same as the constructor argument.
form_initial
Initial form data.
popup_models
Same as in GenericView

Templates used

  1. APP_LABEL / MODEL_NAME _form.html
  2. APP_LABEL / object_form.html
  3. MODEL_NAME _form.html
  4. object_form.html

Context

model
Model of object to be created.
meta
Meta information from the model.
verbose_name
Object verbose name (model._meta.verbose_name).
object_name
Object name (model._meta.object_name.lower()).
form
The form instance for the object.

Example usage:

from softwarefabrica.django.utils.crud import *

author_create = CreateObjectView(model = Author, template_name = "library/author_edit.html")
...

urlpatterns = patterns(
    '',
    url(r'^author/add$',
        author_create,
        name="library-author-create"),
    ...
)

UpdateObjectView

Generic Object Oriented object-update view.

Derives from CreateObjectView.

Constructor arguments

same as in CreateObjectView, and additionally:

template_object_name
variable name to use in context to pass the object to the template.

View call arguments

same as in CreateObjectView, and additionally:

object_id
Primary key of the object to update (either this or slug + slug_field is required).
slug
Slug of object to update (either this or object_id is required)
slug_field
Field to look up slug in (defaults to slug)
template_object_name
Same as the constructor argument.

Templates used

  1. APP_LABEL / MODEL_NAME _form.html
  2. APP_LABEL / object_form.html
  3. MODEL_NAME _form.html
  4. object_form.html

Context

model
Model of object to be updated.
meta
Meta information from the model.
verbose_name
Object verbose name (model._meta.verbose_name).
object_name
Object name (model._meta.object_name.lower()).
form
The form instance for the object.
object
The original object being edited.

Example usage:

from softwarefabrica.django.utils.crud import *

author_edit = UpdateObjectView(model = Author, template_name = "library/author_edit.html")
...

urlpatterns = patterns(
    '',
    url(r'^author/(?P<object_id>[a-zA-Z0-9_\-]+)/edit$',
        author_edit,
        name="library-author-edit"),
    ...
)

DeleteObjectView

Generic Object Oriented object-delete view.

Derives from GenericView.

Constructor arguments

same as in GenericView, and additionally:

post_delete_redirect
URL to redirect to after successful object deletion. If post_delete_redirect is None or an empty string, default is to send to the URL returned by the instance get_absolute_url method.
template_object_name
Template context variable name for the object instance. Defaults to object.
back
URL to redirect to in case the confirmation dialog is cancelled.

View call arguments

same as in GenericView, and additionally:

model
Model of object to be deleted.
object_id
Primary key of the object to delete (either this or slug + slug_field is required).
slug
Slug of object to delete (either this or object_id is required)
slug_field
Field to look up slug in (defaults to slug)
post_delete_redirect
Same as the constructor argument.
template_object_name
Same as the constructor argument.
back
Same as the constructor argument.

Templates used

  1. APP_LABEL / MODEL_NAME _confirm_delete.html
  2. APP_LABEL / object_confirm_delete.html
  3. MODEL_NAME _confirm_delete.html
  4. object_confirm_delete.html

Context

model
Model of object to be deleted.
meta
Meta information from the model.
verbose_name
Object verbose name (model._meta.verbose_name).
object_name
Object name (model._meta.object_name.lower()).
object
The original object being deleted.

Example usage:

from softwarefabrica.django.utils.crud import *

author_delete = DeleteObjectView(model = Author, template_name = "library/author_confirm_delete.html")
...

urlpatterns = patterns(
    '',
    url(r'^author/(?P<object_id>[a-zA-Z0-9_\-]+)/delete$',
        author_delete,
        name="library-author-delete"),
    ...
)

DetailObjectView

Generic Object Oriented object-detail view.

Derives from GenericView.

Constructor arguments

same as in GenericView, and additionally:

queryset
Queryset to retrieve the object from.
template_object_name
Template context variable name for the object instance. Defaults to object.
mimetype
MIME type for the response.
model
Model type of objects to retrieve (optional, derived from queryset if not specified).

View call arguments

same as in GenericView, and additionally:

queryset
Same as the constructor argument.
object_id
Primary key of the object to retrieve (either this or slug + slug_field is required).
slug
Slug of object to retrieve (either this or object_id is required).
slug_field
Field to look up slug in (defaults to slug).
mimetype
Same as the constructor argument.
model
Same as the constructor argument.
template_object_name
Same as the constructor argument.

Templates used

  1. APP_LABEL / MODEL_NAME _detail.html
  2. APP_LABEL / object_detail.html
  3. MODEL_NAME _detail.html
  4. object_detail.html

Context

model
Model of object to be displayed.
meta
Meta information from the model.
verbose_name
Object verbose name (model._meta.verbose_name).
object_name
Object name (model._meta.object_name.lower()).
object
The object displayed.

Example usage:

from softwarefabrica.django.utils.crud import *

author_detail = DetailObjectView(model = Author)
...

urlpatterns = patterns(
    '',
    url(r'^author/(?P<object_id>[a-zA-Z0-9_\-]+)$',
        author_detail,
        name="library-author-detail"),
    ...
)

ListObjectView

Generic Object Oriented object-list view.

Derives from GenericView.

Constructor arguments

same as in GenericView, and additionally:

queryset
Queryset to retrieve objects from.
paginate_by
Number of objects per page.
allow_empty
If False raise an exception on empty queryset (default: True).
template_object_name
Template context variable name for the object instances. Used to determine the template context variable for the object list by appending _list. Defaults to object.
mimetype
MIME type for the response.
model
Model type of objects to retrieve (optional, derived from queryset if not specified).

View call arguments

same as in GenericView, and additionally:

queryset
Same as the constructor argument.
paginate_by
Same as the constructor argument.
page
Page number to display.
allow_empty
Same as the constructor argument.
mimetype
Same as the constructor argument.
model
Same as the constructor argument.
template_object_name
Same as the constructor argument.

Templates used

  1. APP_LABEL / MODEL_NAME _list.html
  2. APP_LABEL / object_list.html
  3. MODEL_NAME _list.html
  4. object_list.html

Context

model
Model of objects to be displayed contained in template_object_name + _list.
meta
Meta information from the model.
verbose_name
Object verbose name (model._meta.verbose_name).
object_name
Object name (model._meta.object_name.lower()).
template_object_name + _list
The list of objects.
is_paginated
True if results are paginated.
paginator
Paginator object.
page_obj
Page instance.
results_per_page
Legacy variable. Number of objects per page (if paginated).
has_next
Legacy variable. True if there is a next page.
has_previous
Legacy variable. True if there is a previous page.
page
Legacy variable. The current page number.
next
Legacy variable. The next page number.
previous
Legacy variable. The previous page number.
pages
Legacy variable. Total number of pages.
hits
Legacy variable. Total number of objects.
last_on_page
Legacy variable. The result number of the last object in template_object_name + _list (1-indexed).
first_on_page
Legacy variable. The result number of the first object in template_object_name + _list (1-indexed).
page_range
Legacy variable. A list of the page numbers (1-indexed).

NOTE: new templates should avoid using legacy context variables and use page_obj instead.

Example usage:

from softwarefabrica.django.utils.crud import *

author_list = ListObjectView(queryset = Author.objects.all(),
                             paginate_by = 10,
                             allow_empty = True)
...

urlpatterns = patterns(
    '',
    url(r'^author/$',
        author_list,
        name="library-author-list"),
    ...
)

create_object

Backward-compatible replacement for django.views.generic.create_update.create_object.

Defined as:

create_object = CreateObjectView()

update_object

Backward-compatible replacement for django.views.generic.create_update.update_object.

Defined as:

update_object = UpdateObjectView()

delete_object

Backward-compatible replacement for django.views.generic.create_update.delete_object.

Defined as:

delete_object = DeleteObjectView()

object_detail

Backward-compatible replacement for django.views.generic.list_detail.object_detail.

Defined as:

object_detail = DetailObjectView()

object_list

Backward-compatible replacement for django.views.generic.list_detail.object_list.

Defined as:

object_list = ListObjectView()