Skip to content

Views

mixins

CRUDViews

Bases: UserPassesTestMixin, SingleTableView

Full CRUD view generator that produces list, create, update, and delete views.

Subclass this and call as_view() to get a set of URL patterns providing a complete CRUD interface backed by django-tables2 for listing and Django generic views for create/update/delete.

Attributes:

Name Type Description
model

The Django model class for this CRUD set.

name

Unique URL namespace prefix. Must be overridden from the default 'crud-view'.

title

Page title displayed in the list view header.

table_fields

List of field names to show in the table. If None, all fields are shown (minus table_exclude).

table_exclude

List of field names to hide from the table.

extra_table_columns

List of extra django-tables2 column tuples (name, Column) appended to the table.

allow_table_ordering

Enable column-header sorting. Defaults to True.

edit_fields

List of field names shown on the edit form.

add_fields

List of field names shown on the add form. Falls back to edit_fields if empty.

allow_edit

Global toggle for edit links. Defaults to True.

allow_delete

Global toggle for delete links. Defaults to True.

allow_add

Global toggle for the "Add" button. Defaults to True.

edit_form_class

Optional custom ModelForm class for edit/add views.

object_title

Human-readable singular name for the model (e.g. 'Person'), used in flash messages.

perms

List of permission strings required to access these views.

base_template

Template that the CRUD templates extend. Required.

raise_exception

If True, raise PermissionDenied instead of redirecting to login. Defaults to True.

additional_index_links

List of extra links shown on the index page.

add_wizard_view_class

Optional SessionWizardView subclass used instead of the default single-step create form.

filters

List of filter definitions. Each entry is either a field name string (auto-detected choices) or a (field, config) tuple where config has keys label, get_choices (callable returning choice tuples), and optionally filter (callable fn(qs, value) -> qs).

filters_widget

Form widget for filter dropdowns.

show_filter_label

Show labels next to filter fields. Defaults to False.

search_fields

List of field lookups for the search box (e.g. ['first_name', 'last_name']). Empty list disables search.

Example
class ManagerPersonView(CRUDViews):
    base_template = 'admin/base_site.html'
    name = 'person_manager'
    model = Person
    table_fields = ['first_name', 'last_name', 'position']
    edit_fields = ['first_name', 'last_name']
    object_title = 'Person'
    filters = [
        'position',
        ('gender', dict(
            label='Gender',
            get_choices=lambda: [('Male', 'Male'), ('Female', 'Female')],
            filter=lambda qs, val: qs.filter(first_name='Naved') if val == 'Male' else qs,
        )),
    ]
    search_fields = ['first_name', 'last_name']

urlpatterns = [
    url(r'^people/', ManagerPersonView.as_view()),
]

get_edit_url_name() classmethod

Return the URL name for the edit view.

Returns:

Type Description

URL name string in the format '{name}_-_edit'.

get_delete_url_name() classmethod

Return the URL name for the delete view.

Returns:

Type Description

URL name string in the format '{name}_-_delete'.

get_add_url_name() classmethod

Return the URL name for the add/create view.

Returns:

Type Description

URL name string in the format '{name}_-_add'.

get_list_url_name() classmethod

Return the URL name for the list/index view.

Returns:

Type Description

URL name string equal to name.

has_perms() classmethod

Check if the current user has the required permissions.

Returns:

Type Description

True if perms is empty or the current user has all listed

permissions.

allow_delete_for_record(record)

Hook to conditionally disable delete for a specific record.

Parameters:

Name Type Description Default
record

The model instance.

required

Returns:

Type Description

True if the record can be deleted.

allow_edit_for_record(record)

Hook to conditionally disable editing for a specific record.

Parameters:

Name Type Description Default
record

The model instance.

required

Returns:

Type Description

True if the record can be edited.

get_extra_table_columns()

Return extra columns to append to the table.

Returns:

Type Description

List of (name, Column) tuples for django-tables2.

get_edit_view_tables(record)

Hook to add extra tables below the edit form.

Parameters:

Name Type Description Default
record

The model instance being edited.

required

Returns:

Type Description

List of django-tables2 table instances to render.

Return extra links to display on the list/index page.

Returns:

Type Description

List of additional link definitions.

get_filters()

Return the list of filter definitions for the index view.

Returns:

Type Description

List of field name strings or (field, config) tuples.

get_search_fields()

Return the list of field lookups used by the search box.

Returns:

Type Description

List of field name strings for __icontains lookups.

get_success_url(type, pk)

Return the URL to redirect to after a successful CRUD operation.

Override this to redirect to a detail page or stay on the edit form.

Parameters:

Name Type Description Default
type

The operation type ('create', 'update', or 'delete').

required
pk

Primary key of the affected object.

required

Returns:

Type Description

URL string or lazy URL.

JSON Views

JSONResponseMixin

Mixin that renders a JSON response from the template view context.

Provides render_to_json_response and get_data methods for use with Django class-based views.

render_to_json_response(context, **response_kwargs)

Return a JsonResponse with the serialized context.

Parameters:

Name Type Description Default
context

View context data.

required
**response_kwargs

Additional kwargs passed to JsonResponse.

{}

Returns:

Name Type Description
JsonResponse

The JSON HTTP response.

get_data(context)

Return the data to be serialized as JSON. Override to customize.

Parameters:

Name Type Description Default
context

View context data.

required

Returns:

Type Description

The context object (default implementation).

JSONView

Bases: JSONResponseMixin, TemplateView

A TemplateView that returns JSON instead of rendered HTML.