literature.ui#

The views a project routes to, and the search and filter definition behind them.

literature.ui.filters#

One module declares what the catalogue is searchable and filterable by, so both the table and the card presentation narrow to the same set of references.

  • SEARCH_FIELDS — the ORM paths a search matches: citation key, the three title fields, container title, every credited contributor’s family, given and literal name, and every identifier’s value. ItemFilterSet.q searches them with CatalogueSearchFilter, django-mvp’s SearchFilter reading each word as a DOI would be stored. The catalogue and the reference picker’s autocomplete view share it.

  • ItemFilterSet — the search and the three filters: item type, issued year and language. It lists every filter explicitly and pins Meta.fields to an empty list, so nothing is generated over fields the catalogue does not filter on. A contributor is found through the search, which matches every credited name.

  • ItemTableFilterSet — ItemFilterSet plus a hidden sort field that carries the table’s column order through the filter form, so applying a filter keeps the sort.

  • LanguageFilter — offers the language values the catalogue actually holds, read from stored data on each request rather than from a fixed list a project has to keep in step.

  • YearFilter — offers the years the catalogue’s issued dates fall in, newest first, read from stored data on each request. Its field, YearChoiceField, still accepts a year that is not on offer, so an old address carrying one narrows to nothing rather than being ignored.

  • annotate_issued — annotates a queryset with issued, taken from the issued date slot. The year filter narrows on it and the table sorts on it.

  • TypeFilter — the item-type filter, any of several types. Its field, TypeChoiceField, declares ScalarOrListSelectMultiple as its own default widget, which is what lets django-mvp’s toolbar draw it as a checkbox dropdown.

  • ScalarOrListSelectMultiple — the item-type widget. It accepts either one stored value or several, so choosing two types widens the result to either of them.

To change what a project’s catalogue filters on, subclass ItemFilterSet and ItemTableFilterSet (or only the one whose view the project uses) and set the subclass as the view’s filterset_class.

Two decisions behind this module are recorded as ADRs: why the searched fields carry no database index (ADR 0024), and why the search and filter definition lives in exactly one place (ADR 0025).

Search and filter definitions for the catalogue, shared by both presentations (FS-010, #96).

class CatalogueSearchFilter(*args: Any, fields: Sequence[str] = (), max_words: int = 10, **kwargs: Any)[source]#

Bases: SearchFilter

django-mvp’s search, with each word read as a DOI would be stored.

A DOI pasted with its https://doi.org/ address or a doi: label in front finds the reference that stores the bare DOI. A word that is only such a prefix searches nothing.

filter(qs, value)[source]#

Strip DOI prefixes from each word, then search as django-mvp does.

class ItemFilterSet(data=None, queryset=None, *, request=None, prefix=None)[source]#

Bases: FilterSet

The catalogue’s search and filters (FS-010, #96): item type, issued year and language.

Search covers contributor names, so there is no separate contributor filter.

class Meta[source]#

Bases: object

fields: list[str] = []#
model#

alias of Item

base_filters = {'issued_year': <literature.ui.filters.YearFilter object>, 'language': <literature.ui.filters.LanguageFilter object>, 'q': <literature.ui.filters.CatalogueSearchFilter object>, 'type': <literature.ui.filters.TypeFilter object>}#
declared_filters = {'issued_year': <literature.ui.filters.YearFilter object>, 'language': <literature.ui.filters.LanguageFilter object>, 'q': <literature.ui.filters.CatalogueSearchFilter object>, 'type': <literature.ui.filters.TypeFilter object>}#
filter_issued_year(queryset, name, value)[source]#

Match a year-only date and a range beginning in it; no issued row excludes.

Narrows on the issued annotation that filter_queryset() applies first. A reference with no issued row annotates to NULL, which __year never matches.

Parameters:
  • queryset – The queryset to narrow.

  • name – The filter’s name. Unused.

  • value – The chosen year.

Returns:

The queryset of references issued in that year.

filter_queryset(queryset)[source]#

Annotate issued and return each match once.

class ItemTableFilterSet(data=None, queryset=None, *, request=None, prefix=None)[source]#

Bases: ItemFilterSet

The catalogue’s filters plus the table’s own ordering, carried by the form.

The table sorts through django-tables2’s sort query parameter. The filter form is a plain GET form, so a hidden field here keeps the chosen column order when the form is submitted again.

base_filters = {'issued_year': <literature.ui.filters.YearFilter object>, 'language': <literature.ui.filters.LanguageFilter object>, 'q': <literature.ui.filters.CatalogueSearchFilter object>, 'sort': <django_filters.filters.CharFilter object>, 'type': <literature.ui.filters.TypeFilter object>}#
declared_filters = {'issued_year': <literature.ui.filters.YearFilter object>, 'language': <literature.ui.filters.LanguageFilter object>, 'q': <literature.ui.filters.CatalogueSearchFilter object>, 'sort': <django_filters.filters.CharFilter object>, 'type': <literature.ui.filters.TypeFilter object>}#
filter_sort(queryset, name, value)[source]#

Leave the queryset alone; sort only round-trips the table’s ordering.

Parameters:
  • queryset – The queryset, returned unchanged.

  • name – The filter’s name. Unused.

  • value – The chosen column order. Unused.

Returns:

The queryset.

class LanguageFilter(*args, **kwargs)[source]#

Bases: ChoiceFilter

The distinct language values the catalogue holds, as stored.

Not django-filter’s AllValuesFilter, which also offers the empty string, and language is blank on most references. The choices are recomputed per request, as each request builds a new ItemFilterSet.

property field#

The choice field, its choices refreshed from the stored language values.

SEARCH_FIELDS = ['citation_key', 'title', 'title_short', 'original_title', 'container_title', 'item_names__name__family', 'item_names__name__given', 'item_names__name__literal', 'item_identifiers__value']#

the item’s identity and title fields, every contributor’s name parts whatever the role, and its identifiers.

Type:

The ORM paths a catalogue search matches

class ScalarOrListSelectMultiple(attrs=None, choices=())[source]#

Bases: SelectMultiple

Accept a bare stored value as well as a list of them, and drop blanks.

SelectMultiple reads a list from a QueryDict but a bare value from a plain dict, and ItemFilterSet is also built directly from a dict. A blank entry is dropped because ?type= must mean no filter: MultipleChoiceField would reject a list holding an empty string and turn a cleared filter into an empty catalogue.

property media#
value_from_datadict(data, files, name)[source]#

Widen a bare stored value to a one-item list, and drop blank entries.

class TypeChoiceField(*args, **kwargs)[source]#

Bases: MultipleChoiceField

A multiple choice field whose own widget accepts a bare value.

The widget is the field’s default, not passed per filter, so django-mvp’s toolbar recognises a plain multiple choice and draws its own dropdown.

widget#

alias of ScalarOrListSelectMultiple

class TypeFilter(*args, **kwargs)[source]#

Bases: MultipleChoiceFilter

Item type, any of several, through TypeChoiceField.

field_class#

alias of TypeChoiceField

class YearChoiceField(*args, **kwargs)[source]#

Bases: ChoiceField

A choice of the years held that still accepts any other year.

A year no reference was issued in, from an old bookmark, narrows the catalogue to nothing rather than being dropped as an invalid choice and showing every reference (FS-010). A value that is not a year, or a year outside the 1 to 9999 a Python date can hold, is still invalid, so the filter ignores it rather than failing on the date lookup.

valid_value(value)[source]#

Accept a listed year or any other year a date can hold.

Parameters:

value – The submitted year.

Returns:

True if the value is a valid choice.

class YearFilter(*args, **kwargs)[source]#

Bases: ChoiceFilter

The issued years the catalogue holds, newest first, through YearChoiceField.

property field#

The choice field, its choices refreshed from the stored issued years.

field_class#

alias of YearChoiceField

annotate_issued(queryset)[source]#

Annotate issued from the issued date slot’s begin.

A Subquery rather than a join, as a join multiplies the rows of an item carrying more than one ItemDate and corrupts a paginator’s count.

Parameters:

queryset – The Item queryset to annotate.

Returns:

The queryset with an issued annotation.

literature.ui.picker#

The reference picker for a project’s own forms. ReferenceField chooses one reference and ReferenceMultipleField chooses several. Both are django-tomselect model fields whose default configuration points at the catalogue’s autocomplete route, literature:item-autocomplete. A config passed to either is merged over that default. Both inherit that default and the restriction check from ReferencePickerMixin, which is not used on its own. They also refuse a chosen reference outside the configuration’s constant filter_by and exclude_by conditions. item_label names a reference the same way in the control and in the search results: its title or citation key, its year and its first contributor. How to use them is in The reference picker.

Searchable fields for choosing references in a project’s own form.

class ReferenceField(*args, config=None, **kwargs)[source]#

Bases: ReferencePickerMixin, TomSelectModelChoiceField

Choose one reference by searching the catalogue.

On a plain form, declare it as an attribute. On a model form, name it in Meta.field_classes so Django builds it from the model field.

class ReferenceMultipleField(*args, config=None, **kwargs)[source]#

Bases: ReferencePickerMixin, TomSelectModelMultipleChoiceField

Choose several references by searching the catalogue.

Declared the same way as ReferenceField.

class ReferencePickerMixin(*args, config=None, **kwargs)[source]#

Bases: object

What the two reference fields share: a default config and a restriction check.

The default config points django-tomselect at the package’s search route. A config the developer passes is merged over it, so any django-tomselect setting can be added. django-tomselect validates a submission against the search view’s whole queryset, so a chosen reference is also checked against the config’s constant filter_by and exclude_by conditions. A condition that takes its value from another form field is left to django-tomselect.

Parameters:
  • *args – What the django-tomselect field takes.

  • config – A TomSelectConfig or a dict of its settings, merged over default_config.

  • **kwargs – What the django-tomselect field takes.

clean(value)[source]#

Refuse a chosen reference outside the config’s constant conditions.

static constant_value(spec)[source]#

Return a constant condition’s value, split when its lookup takes a list.

Parameters:

spec – A normalized filter_by or exclude_by condition.

Returns:

The condition’s value.

default_config = TomSelectConfig(url='literature:item-autocomplete', show_list=False, show_create=False, show_detail=False, show_update=False, show_delete=False, value_field='id', label_field='label', create_field='', filter_by=(), exclude_by=(), use_htmx=False, attrs={}, close_after_select=None, hide_placeholder=None, highlight=True, hide_selected=True, load_throttle=300, loading_class='loading', max_items=None, max_options=None, open_on_focus=True, placeholder='Select a value', preload='focus', create=False, create_filter=None, create_with_htmx=False, minimum_query_length=1, css_framework='default', use_minified=False, plugin_checkbox_options=None, plugin_clear_button=None, plugin_dropdown_header=None, plugin_dropdown_footer=None, plugin_dropdown_input=None, plugin_remove_button=None)#
within_restriction(pks)[source]#

Return whether every pk meets the constant conditions.

Parameters:

pks – The primary keys of the chosen references.

Returns:

True if all of them satisfy the config’s constant conditions.

item_label(item: Item) → str[source]#

Return the text that names a reference wherever the picker shows it.

The title (the citation key when there is none), then the issued year in brackets, then the first contributor. Whatever a reference lacks is left out. Reads item_dates and item_names through .all(), so items loaded with those prefetched are labelled without a query.

Parameters:

item – The reference to label.

Returns:

The label.

literature.ui.views#

ItemTableView serves the catalogue as a table and ItemListView serves it as cards. Either can back the catalogue route, chosen through the CATALOGUE_VIEW setting — see ADR 0033 for why the choice is made this way rather than by routing.

ReferenceAutocompleteView is a django-tomselect AutocompleteModelView that answers the reference picker’s searches as JSON, at most SEARCH_LIMIT references at a time, each with its id and label, under the route name literature:item-autocomplete. It is open to everyone, like the catalogue list. Text containing a NUL character answers 400. No text answers the first page of the catalogue by title.

CatalogueListMixin carries the card configuration that ItemListView and ContributorDetailView share — the model, the card template, the page title and the prefetching a row needs. The contributor page composes it without the search box and filters, which belong to the catalogue alone.

ItemTableView draws the search box and every filter in its toolbar, and leaves out a choice filter the catalogue holds nothing for, such as Language when no reference records one. Its template, literature/ui/item_table_page.html, redraws django-mvp’s toolbar row to put Import at the end of it, since django-mvp offers no block in that row (django-mvp/django-mvp#579). ItemListView renders django-mvp’s list page as it ships, with the filters in a drawer opened from the toolbar at every screen width.

ItemImportView serves the import page, reached from the Import action on the table catalogue. It renders the format choice and file control on a GET. On a valid POST it stages the uploaded file and redirects to the preview. Where the reader ticked the skip-preview control it instead runs the chosen format immediately and renders the report in that same response, which is the only path that still does.

ItemImportPreviewView serves the preview at an address of its own. It holds no result: every GET reads the staged file back and runs the format over it again with dry_run=True, so reloading the address reports the same outcomes and writes nothing either time. It carries no import form. The rows it hands the table each carry the outcome the filter below matches on, and the counts it renders above the table come straight off the report, so narrowing the table never changes them. Reaching the address with nothing staged sets nothing_staged in the context and renders a notice rather than raising.

ItemImportRestartView discards the staged file, clears what the session held about it, and redirects to an empty import form. It answers POST only.

ItemImportConfirmView carries out the import a preview described, then redirects to the catalogue with a message stating the counts. It renders no template of its own and there is no success page: the per-entry detail was on the preview, and the message here confirms what that preview said would happen. It takes no file and no token from the page, both coming from the reader’s own session, so a request can only confirm a file that same session staged. A confirmation naming a preview the session has since replaced, or one whose file is gone, returns to the catalogue with a message saying there was nothing to confirm and imports nothing. A GET has nothing to show without a prior preview and redirects back to the import page.

The routes these views are reachable at, all within the literature namespace:

  • literature:item-import — the format choice and file control.

  • literature:item-import-preview — the preview page.

  • literature:item-import-restart — discard the staged file and start again.

  • literature:item-import-confirm — carry out the previewed import.

See Importing a bibliography file for what a reader sees.

Permissions#

Every view that changes the catalogue uses Django’s PermissionRequiredMixin, with permission_required set to one of three module constants (ADR 0036):

Views

Constant

Permission

ItemCreateView, and the four import views

ADD_PERMISSION

literature.add_item

ItemUpdateView

CHANGE_PERMISSION

literature.change_item

ItemDeleteView

DELETE_PERMISSION

literature.delete_item

The list, detail and contributor views check nothing. Their Add, Import, Edit and Delete actions are drawn through HasPermission, a callable show_<action>_action flag that django-mvp calls with the request user, so a user sees only the actions their permissions open. To apply a different rule, subclass the view and set permission_required, or override has_permission():

from literature.ui.views import ItemDeleteView


class StaffOnlyDeleteView(ItemDeleteView):
    def has_permission(self):
        return self.request.user.is_staff

Views for the opt-in front end.

ADD_PERMISSION = 'literature.add_item'#

The model permission each write page asks for. Importing creates references, so it asks for the same permission as adding one.

CATALOGUE_NAME_PLURAL = 'publications'#

The same word mid-sentence, a message of its own because lowercasing is wrong for languages that capitalise their nouns.

CATALOGUE_TITLE = 'Publications'#

What the catalogue calls itself wherever a reader is shown its name. Set here because renaming the model would also rename it in the admin and migrations.

CRUD_VIEWS = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#

under this app’s app_name a bare reverse("item-list") raises NoReverseMatch.

Type:

CRUD action to namespaced URL name, shared by every view

class CatalogueListMixin[source]#

Bases: object

The card-list configuration ItemListView and ContributorDetailView share.

Subclassing ItemListView directly would hand the contributor page a search box and filters it must not have.

crud_views = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
directory: list[str] = ['create']#
get_model_info()[source]#

Name the collection CATALOGUE_NAME_PLURAL, not the model’s own name.

get_queryset()[source]#

Prefetch what the reference component reads, for a constant query count.

list_item_template = 'literature/ui/item_list_item.html'#
model#

alias of Item

page_title = 'Publications'#
show_create_action = <literature.ui.views.HasPermission object>#
class ContributorDetailView(**kwargs)[source]#

Bases: CatalogueListMixin, MVPListView

The contributor page (FS-006, #55).

A contributor’s page is the catalogue filtered to what they are credited on, so it composes CatalogueListMixin. It declares no filterset, so it has no search box or filter.

property contributor[source]#

Return the contributor, resolved once per request before the queryset is built.

empty_state_heading: str | Promise | None = 'Not credited on anything yet'#
empty_state_message: str | Promise | None = 'This contributor has no credited references in the catalogue.'#
get_breadcrumbs()[source]#

Link back to the catalogue, then name this contributor.

get_page_title()[source]#

Title the page with the contributor’s own name, unsplit.

get_queryset()[source]#

Filter the catalogue to items crediting this contributor, deduplicated.

class HasPermission(permission)[source]#

Bases: object

A show_<action>_action flag that draws a link only for users holding permission.

django-mvp calls a callable flag with the request user. Hiding the link is courtesy only: the page it points at checks the same permission itself.

Parameters:

permission – The permission to check, such as "literature.add_item".

IMPORT_PREVIEW_SESSION_KEY = 'literature_import_preview'#

Which preview a confirmation is confirming; previewing again supersedes it. Unlike the token this is safe to render, as alone it authorises nothing.

IMPORT_TOKEN_SESSION_KEY = 'literature_import_token'#

The session keys carrying a staged file’s identity from preview to confirm. They never reach the page, so a request can only confirm what its own session staged.

ITEM_INLINES = [<class 'literature.ui.inlines.ContributorInline_author'>, <class 'literature.ui.inlines.ContributorInline_editor'>, <class 'literature.ui.inlines.ContributorInline_chair'>, <class 'literature.ui.inlines.ContributorInline_collection_editor'>, <class 'literature.ui.inlines.ContributorInline_compiler'>, <class 'literature.ui.inlines.ContributorInline_composer'>, <class 'literature.ui.inlines.ContributorInline_container_author'>, <class 'literature.ui.inlines.ContributorInline_contributor'>, <class 'literature.ui.inlines.ContributorInline_curator'>, <class 'literature.ui.inlines.ContributorInline_director'>, <class 'literature.ui.inlines.ContributorInline_editorial_director'>, <class 'literature.ui.inlines.ContributorInline_executive_producer'>, <class 'literature.ui.inlines.ContributorInline_guest'>, <class 'literature.ui.inlines.ContributorInline_host'>, <class 'literature.ui.inlines.ContributorInline_illustrator'>, <class 'literature.ui.inlines.ContributorInline_interviewer'>, <class 'literature.ui.inlines.ContributorInline_narrator'>, <class 'literature.ui.inlines.ContributorInline_organizer'>, <class 'literature.ui.inlines.ContributorInline_original_author'>, <class 'literature.ui.inlines.ContributorInline_performer'>, <class 'literature.ui.inlines.ContributorInline_producer'>, <class 'literature.ui.inlines.ContributorInline_recipient'>, <class 'literature.ui.inlines.ContributorInline_reviewed_author'>, <class 'literature.ui.inlines.ContributorInline_script_writer'>, <class 'literature.ui.inlines.ContributorInline_series_creator'>, <class 'literature.ui.inlines.ContributorInline_translator'>, <class 'literature.ui.inlines.IdentifierInline'>]#

The related-row sets composed on both the create and update pages.

class ItemCreateView(**kwargs)[source]#

Bases: PermissionRequiredMixin, MVPCreateView

Enter a reference by hand (FS-008, #74).

The reference’s contributors and identifiers are created in the same transaction as the reference itself through inlines.

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
form_class#

alias of ItemForm

get_context_data(**kwargs)[source]#

Add the field-group and contributor-datalist context the write form needs.

inlines: list[type[InlineFormSet]] = [<class 'literature.ui.inlines.ContributorInline_author'>, <class 'literature.ui.inlines.ContributorInline_editor'>, <class 'literature.ui.inlines.ContributorInline_chair'>, <class 'literature.ui.inlines.ContributorInline_collection_editor'>, <class 'literature.ui.inlines.ContributorInline_compiler'>, <class 'literature.ui.inlines.ContributorInline_composer'>, <class 'literature.ui.inlines.ContributorInline_container_author'>, <class 'literature.ui.inlines.ContributorInline_contributor'>, <class 'literature.ui.inlines.ContributorInline_curator'>, <class 'literature.ui.inlines.ContributorInline_director'>, <class 'literature.ui.inlines.ContributorInline_editorial_director'>, <class 'literature.ui.inlines.ContributorInline_executive_producer'>, <class 'literature.ui.inlines.ContributorInline_guest'>, <class 'literature.ui.inlines.ContributorInline_host'>, <class 'literature.ui.inlines.ContributorInline_illustrator'>, <class 'literature.ui.inlines.ContributorInline_interviewer'>, <class 'literature.ui.inlines.ContributorInline_narrator'>, <class 'literature.ui.inlines.ContributorInline_organizer'>, <class 'literature.ui.inlines.ContributorInline_original_author'>, <class 'literature.ui.inlines.ContributorInline_performer'>, <class 'literature.ui.inlines.ContributorInline_producer'>, <class 'literature.ui.inlines.ContributorInline_recipient'>, <class 'literature.ui.inlines.ContributorInline_reviewed_author'>, <class 'literature.ui.inlines.ContributorInline_script_writer'>, <class 'literature.ui.inlines.ContributorInline_series_creator'>, <class 'literature.ui.inlines.ContributorInline_translator'>, <class 'literature.ui.inlines.IdentifierInline'>]#
list_view_title = 'Publications'#
model#

alias of Item

page_title: str | Promise = 'Add %(verbose_name)s'#
permission_required = 'literature.add_item'#
show_detail_action = True#
show_list_action = True#
success_message = '%(verbose_name)s added to the catalogue.'#
template_name = 'literature/ui/item_form.html'#
class ItemDeleteView(**kwargs)[source]#

Bases: PermissionRequiredMixin, MVPDeleteView

Remove a reference that does not belong (FS-008, #74).

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
get_back_url() → str[source]#

Decline and land back on the reference, not the catalogue.

model#

alias of Item

page_title: str | Promise = 'Delete %(verbose_name)s'#
permission_required = 'literature.delete_item'#
show_detail_action = True#
show_list_action = True#
success_message = '%(verbose_name)s deleted.'#
success_url = 'list'#
class ItemDetailView(**kwargs)[source]#

Bases: MVPDetailView

The reference page (FS-006, #55).

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
directory: list[str] = ['update', 'delete']#

Actions offered in the page header, each still gated by its show_* flag. The list action is left out because the breadcrumb trail already links it.

get_context_data(**kwargs)[source]#

Add field sections, grouped contributors and linkable identifiers.

get_page_title()[source]#

Title the page with the full title; str() cuts it at 80 characters.

get_queryset()[source]#

Prefetch the related rows the page renders.

list_view_title = 'Publications'#
model#

alias of Item

page_width: PageWidth = 'medium'#
show_delete_action = <literature.ui.views.HasPermission object>#
show_list_action = True#
show_update_action = <literature.ui.views.HasPermission object>#
template_name = 'literature/ui/item_detail.html'#
class ItemImportConfirmView(**kwargs)[source]#

Bases: PermissionRequiredMixin, View

Carry out the import a preview described, then return to the catalogue.

FS-011, #103. The staged file’s token and format come from the reader’s own session, never from the page. Every outcome, including one with nothing to confirm, returns to the catalogue through the messages framework.

get(request, *args, **kwargs)[source]#

Refuse a bare GET; confirming is a POST-only action.

permission_required = 'literature.add_item'#
post(request, *args, **kwargs)[source]#

Import the staged file if this session’s preview matches, else refuse.

class ItemImportPreviewView(**kwargs)[source]#

Bases: PermissionRequiredMixin, MVPFormView

Rebuild the preview from the staged file on every GET (FS-011, #103).

A dry run, not a stored result: reloading re-reads the staged file and changes nothing. form_class is set only because MVPFormView wants one; the confirm control’s hidden field is built from the session.

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
form_class#

alias of ConfirmImportForm

get(request, *args, **kwargs)[source]#

Re-run the dry run against the staged file and render its report.

http_method_names = ['get', 'head', 'options']#
list_view_title = 'Publications'#
model#

alias of Item

page_subtitle: str | Promise = 'What importing this file would do. Nothing has been imported yet.'#
page_title: str | Promise = 'Preview import'#
permission_required = 'literature.add_item'#
show_list_action = True#
template_name = 'literature/ui/import_preview.html'#
class ItemImportRestartView(**kwargs)[source]#

Bases: PermissionRequiredMixin, View

Discard the staged file and return to an empty import form (FS-011, #103).

permission_required = 'literature.add_item'#
post(request, *args, **kwargs)[source]#

Discard the session’s staged file and redirect to a fresh import form.

class ItemImportView(**kwargs)[source]#

Bases: PermissionRequiredMixin, MVPFormView

Choose a format and a file (FS-011, #103).

model = Item although the form is not a ModelForm: MVPFormView raises ImproperlyConfigured with no model, and the breadcrumb belongs under the catalogue.

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
discard_staging()[source]#

Drop whatever this session had staged, and return the staging.

Both submission paths supersede an earlier preview, which this session can no longer reach, so nothing should hold its file any longer.

Returns:

The StagedUpload used, ready to stage the next file.

dispatch(request, *args, **kwargs)[source]#

Sweep abandoned stagings before every entry to this view.

form_class#

alias of ImportForm

form_valid(form)[source]#

Import directly if previewing is skipped, else stage the file to preview.

list_view_title = 'Publications'#
model#

alias of Item

page_title: str | Promise = 'Import references'#
permission_required = 'literature.add_item'#
show_list_action = True#
template_name = 'literature/ui/import_form.html'#
class ItemListView(**kwargs)[source]#

Bases: CatalogueListMixin, MVPListView

The catalogue list (FS-006, #55).

directory: list[str] = ['create', 'import']#
empty_state_heading: str | Promise | None = 'Nothing in the catalogue yet'#
empty_state_message: str | Promise | None = 'References imported or created will appear here.'#
filter_panel_attrs: dict = {'breakpoint': False, 'position': 'end'}#
filterset_class#

alias of ItemFilterSet

get_url_kwargs(action)[source]#

Resolve “import” as collection-level, like the “list”/”create” default.

show_import_action = <literature.ui.views.HasPermission object>#
toolbar_filters: list[str] = ['q']#
class ItemTableView(**kwargs)[source]#

Bases: MVPTableView

The catalogue as a table (FS-009, #87).

urls.py points the item-list route at it by default (docs/adr/0033-the-catalogue-view-is-chosen-by-a-setting.md).

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
directory: list[str] = ['create', 'import']#
empty_state_heading: str | Promise | None = 'Nothing in the catalogue yet'#
empty_state_message: str | Promise | None = 'References imported or created will appear here.'#
filter_panel_attrs: dict = {'breakpoint': False, 'position': 'end'}#
filterset_class#

alias of ItemTableFilterSet

get_active_filters(filterset)[source]#

Leave the hidden sort field, the table’s own ordering, out of the count.

get_context_data(**kwargs)[source]#

Leave out empty choices, and draw the hidden sort field in the toolbar’s form.

get_model_info()[source]#

Name the collection CATALOGUE_NAME_PLURAL, not the model’s own name.

get_queryset()[source]#

Prefetch what the credited-names and issued cells read.

get_url_kwargs(action)[source]#

Resolve “import” as collection-level, like the “list”/”create” default.

model#

alias of Item

page_title: str | Promise = 'Publications'#
paginate_by = 24#
show_create_action = <literature.ui.views.HasPermission object>#
show_import_action = <literature.ui.views.HasPermission object>#
table_class#

alias of ItemTable

template_name = 'literature/ui/item_table_page.html'#
toolbar_filters: list[str] = ['q', 'type', 'issued_year', 'language']#
class ItemUpdateView(**kwargs)[source]#

Bases: PermissionRequiredMixin, MVPUpdateView

Correct a reference that is wrong (FS-008, #74).

The reference’s contributors and identifiers are saved in the same transaction as the reference itself through inlines.

crud_views: dict[str, str] = {'create': 'literature:{model_name}-create', 'delete': 'literature:{model_name}-delete', 'detail': 'literature:{model_name}-detail', 'import': 'literature:{model_name}-import', 'list': 'literature:{model_name}-list', 'update': 'literature:{model_name}-update'}#
form_class#

alias of ItemForm

get_context_data(**kwargs)[source]#

Add the same context as create, plus this page’s forced-visible groups.

inlines: list[type[InlineFormSet]] = [<class 'literature.ui.inlines.ContributorInline_author'>, <class 'literature.ui.inlines.ContributorInline_editor'>, <class 'literature.ui.inlines.ContributorInline_chair'>, <class 'literature.ui.inlines.ContributorInline_collection_editor'>, <class 'literature.ui.inlines.ContributorInline_compiler'>, <class 'literature.ui.inlines.ContributorInline_composer'>, <class 'literature.ui.inlines.ContributorInline_container_author'>, <class 'literature.ui.inlines.ContributorInline_contributor'>, <class 'literature.ui.inlines.ContributorInline_curator'>, <class 'literature.ui.inlines.ContributorInline_director'>, <class 'literature.ui.inlines.ContributorInline_editorial_director'>, <class 'literature.ui.inlines.ContributorInline_executive_producer'>, <class 'literature.ui.inlines.ContributorInline_guest'>, <class 'literature.ui.inlines.ContributorInline_host'>, <class 'literature.ui.inlines.ContributorInline_illustrator'>, <class 'literature.ui.inlines.ContributorInline_interviewer'>, <class 'literature.ui.inlines.ContributorInline_narrator'>, <class 'literature.ui.inlines.ContributorInline_organizer'>, <class 'literature.ui.inlines.ContributorInline_original_author'>, <class 'literature.ui.inlines.ContributorInline_performer'>, <class 'literature.ui.inlines.ContributorInline_producer'>, <class 'literature.ui.inlines.ContributorInline_recipient'>, <class 'literature.ui.inlines.ContributorInline_reviewed_author'>, <class 'literature.ui.inlines.ContributorInline_script_writer'>, <class 'literature.ui.inlines.ContributorInline_series_creator'>, <class 'literature.ui.inlines.ContributorInline_translator'>, <class 'literature.ui.inlines.IdentifierInline'>]#
model#

alias of Item

page_title: str | Promise = 'Edit %(verbose_name)s'#
permission_required = 'literature.change_item'#
show_detail_action = True#
show_list_action = True#
success_message = '%(verbose_name)s updated.'#
template_name = 'literature/ui/item_form.html'#
class ReferenceAutocompleteView(**kwargs)[source]#

Bases: AutocompleteModelView

Answer a reference picker’s search with the references that match.

Matches the text against title, citation key, a contributor’s family or literal name and a DOI, ranking a title or citation key that starts with the text first. Each result carries the reference’s id and its label.

The route is open to everyone, as the catalogue list is (docs/adr/0022-the-front-ends-pages-are-open.md).

allow_anonymous = True#
get(request, *args, **kwargs)[source]#

Refuse a NUL character before any query.

hook_prepare_results(results)[source]#

Label each result, reading the page’s references once.

model#

alias of Item

order_queryset(queryset)[source]#

Put a title or citation key that starts with the text first, then by title.

page_size = 20#
static prepare_label(item)[source]#

Label a reference chosen in a field the way a search result is labelled.

search(queryset, query)[source]#

Keep the references the catalogue’s own search finds, and rank them.

search_lookups = []#
setup(request, *args, **kwargs)[source]#

Cut the text to SEARCH_TEXT_LIMIT and hold the page to SEARCH_LIMIT.

skip_authorization = True#
value_fields = ['label']#
virtual_fields = ['label']#
SEARCH_LIMIT = 20#

The most references one search answers with.

SEARCH_TEXT_LIMIT = 200#

The most characters of a search the view reads; the rest is dropped.

TYPE_DATES_JSON = '{"article": [], "article-journal": ["available-date"], "article-magazine": [], "article-newspaper": [], "bill": [], "book": ["original-date"], "broadcast": [], "chapter": [], "classic": ["original-date"], "collection": [], "dataset": [], "document": [], "entry": [], "entry-dictionary": [], "entry-encyclopedia": [], "event": ["event-date"], "figure": [], "graphic": [], "hearing": [], "interview": [], "legal_case": [], "legislation": [], "manuscript": ["submitted"], "map": [], "motion_picture": [], "musical_score": [], "pamphlet": [], "paper-conference": ["event-date"], "patent": [], "performance": ["event-date"], "periodical": [], "personal_communication": [], "post": ["accessed"], "post-weblog": [], "regulation": [], "report": [], "review": [], "review-book": [], "software": [], "song": [], "speech": ["event-date"], "standard": [], "thesis": [], "treaty": ["available-date"], "webpage": ["accessed"]}'#

The date slots and contributor roles each type leads with, serialised once into every write page beside TYPE_GROUPS_JSON.

TYPE_GROUPS_JSON = '{"article": ["core", "general", "numbering"], "article-journal": ["container", "core", "general", "numbering"], "article-magazine": ["container", "core", "general", "numbering"], "article-newspaper": ["container", "core", "general", "numbering"], "bill": ["core", "general", "legal", "numbering"], "book": ["container", "core", "general", "numbering", "original", "publication"], "broadcast": ["container", "core", "general", "publication"], "chapter": ["container", "core", "general", "numbering"], "classic": ["archive", "core", "general", "original"], "collection": ["archive", "core", "general"], "dataset": ["core", "general"], "document": ["core", "general"], "entry": ["container", "core", "general", "numbering"], "entry-dictionary": ["container", "core", "general", "numbering"], "entry-encyclopedia": ["container", "core", "general", "numbering"], "event": ["core", "event", "general"], "figure": ["archive", "core", "general", "publication"], "graphic": ["archive", "core", "general", "publication"], "hearing": ["core", "general", "legal", "numbering"], "interview": ["core", "general"], "legal_case": ["core", "general", "legal", "numbering"], "legislation": ["core", "general", "legal", "numbering"], "manuscript": ["archive", "core", "general"], "map": ["core", "general", "physical"], "motion_picture": ["container", "core", "general"], "musical_score": ["core", "general"], "pamphlet": ["archive", "core", "general"], "paper-conference": ["container", "core", "event", "general", "numbering"], "patent": ["core", "general", "legal", "numbering"], "performance": ["core", "event", "general"], "periodical": ["core", "general"], "personal_communication": ["archive", "core", "general"], "post": ["core", "general"], "post-weblog": ["core", "general"], "regulation": ["core", "general", "legal", "numbering"], "report": ["container", "core", "general", "numbering"], "review": ["container", "core", "general", "numbering", "review"], "review-book": ["container", "core", "general", "numbering", "review"], "software": ["core", "general", "publication"], "song": ["container", "core", "general", "numbering"], "speech": ["container", "core", "event", "general", "publication"], "standard": ["core", "general", "numbering"], "thesis": ["core", "general", "publication"], "treaty": ["core", "general", "legal", "numbering"], "webpage": ["container", "core", "general"]}'#

Every ItemType value mapped to the group names its form shows by default, serialised once into every write page.

contributor_datalist_context()[source]#

Build the stored-name suggestions a contributor row’s input reads via list=.

Returns:

The datalist id and the family names to offer.

field_group_context(form, inlines, forced_groups=frozenset({}))[source]#

Build the write form’s template context.

A group holding a field with an error joins the forced groups, so an error is never drawn inside a section the page has hidden.

Parameters:
  • form – The bound or unbound ItemForm.

  • inlines – The contributor sets followed by the identifier set.

  • forced_groups – Groups already holding a value on the object being edited (FieldGroups.groups_holding_values), shown whatever the item type.

Returns:

The context entries the write form’s template reads.

form_problems(form, inlines)[source]#

Collect every error on the page, in page order, each with the id of the field to fix.

Drawn as one summary above the form, since an error may sit in a tab the person is not looking at.

Parameters:
  • form – The bound ItemForm.

  • inlines – The contributor sets followed by the identifier set.

Returns:

A list of {"message", "target"} dicts; target is empty for an error that belongs to no field.

The write pages hand their template form_problems(): every error on the form and its sets, in page order, each with the id of the field to fix, for the summary drawn above the tabs.

literature.ui.forms#

ImportForm is the format choice, file control and skip-preview checkbox the import page renders — a plain forms.Form, not a ModelForm, since nothing on it maps to Item directly. The format resolves the file into entries and the entries into items, never this form. Its format choices are read from available_formats() when the form is instantiated, not when the class is defined, so a format configured after import time still appears. The skip-preview checkbox is unticked by default, so a plain submission previews rather than imports. ItemForm is the one write form every create and update page shares — see the README’s “Adding, editing and removing a reference” section for what it does. Besides every scalar field of Item, it declares one date field per CSL date slot, named by date_field_name() in the order DATE_SLOTS gives, and writes each slot’s ItemDate when it saves. StoredPartialDateField shows a stored partial date as the text it saves as. KeywordsField takes keywords as tags and stores them as the one comma-separated string CSL JSON keeps, offering every keyword the catalogue already uses through keyword_choices(). ItemIdentifierForm takes its identifier type through an OpenChoiceField, which accepts a type outside its choices. CreatableSelect and CreatableSelectMultiple are the Tom Select controls that let a person type a value in beside the choices offered.

literature.ui.formlayout#

ItemFormLayout builds the write form’s crispy layout: the four tabs, the type-scoped sections in SECTION_ORDER, the dates and the contributor sets. Each section, date slot and role set is shown or hidden in the browser by the condition shown_when(), date_shown_when() or role_shown_when() writes for it, and rows_of() lays a run of fields out in equal columns. TYPE_CHOICE_GROUPS sorts the 45 item types into the groups the type control offers them in, and FIELD_LABELS and FIELD_HELP hold the copy a person reads in place of the model’s own CSL notes. The contributor sets themselves are CONTRIBUTOR_INLINES in literature.ui.inlines, one per role in ROLE_ORDER, and which roles each type leads with is TYPE_ROLES in literature.ui.fieldgroups.

How the write form is arranged on the page: tabs, sections and the copy a person reads (FS-008).

DATE_SLOTS = ((DateType.SUBMITTED, 'Submitted'), (DateType.ISSUED, 'Published'), (DateType.AVAILABLE_DATE, 'Available online'), (DateType.EVENT_DATE, 'Event date'), (DateType.ORIGINAL_DATE, 'Originally published'), (DateType.ACCESSED, 'Accessed'))#

The six CSL date slots as they read on the form, in the order of a reference’s life.

FIELD_HELP = {'annote': 'For an annotated bibliography.', 'archive_location': 'Such as a box and folder.', 'authority': 'The court, agency or office that issued it.', 'citation_key': 'A short handle for citing it, such as shannon1948. It need not be unique.', 'container_title': 'The journal, book, website or programme it appeared in.', 'dimensions': 'Such as 30 × 40 cm, or a running time.', 'edition': 'Such as 2nd or revised.', 'event_title': 'The conference, exhibition or other event.', 'genre': 'Such as PhD thesis or technical report.', 'journal_abbreviation': 'As citation styles print it, such as Bell Syst. Tech. J.', 'jurisdiction': 'Such as a country or state.', 'keyword': 'Separate keywords with commas.', 'language': 'A language tag, such as en or de.', 'medium': 'Such as print, CD or online.', 'note': 'Some citation styles print this after the reference.', 'number': 'A report, patent, bill or standard number.', 'original_title': 'Its title in the original language, for a translation.', 'page': 'A single page or a range, such as 379–423.', 'reviewed_genre': 'Such as book or film.', 'scale': 'Such as 1:50,000.', 'source': 'The library catalogue or database it was found in.', 'status': 'Only for work not yet published, such as forthcoming or in press.', 'title_short': 'For citation styles that cite a work in short after its first mention.', 'version': 'Of software or a dataset, such as 2.1.0.'}#

Help only where a label alone leaves the person guessing. Every other field draws none, rather than the model’s CSL JSON mapping note.

FIELD_LABELS = {'annote': 'Annotation', 'archive_collection': 'Collection', 'archive_location': 'Location in the archive', 'archive_place': 'Place of the archive', 'collection_number': 'Number in series', 'collection_title': 'Series', 'container_title': 'Title', 'container_title_short': 'Short title', 'event_place': 'Place', 'event_title': 'Event', 'keyword': 'Keywords', 'original_publisher_place': 'Original place of publication', 'page': 'Pages', 'page_first': 'First page', 'publisher_place': 'Place of publication', 'references': 'Procedural history', 'reviewed_genre': 'Reviewed genre', 'reviewed_title': 'Title of the reviewed work', 'status': 'Publication status', 'title_short': 'Short title', 'volume_title_short': 'Short volume title'}#

Labels where the model’s verbose_name is the CSL variable’s name rather than what a person would call it.

class ItemFormLayout(form)[source]#

Bases: object

The write form’s arrangement, for one form instance.

Four tabs: the reference itself, its contributors, its identifiers, and notes with the fields most references never need.

Parameters:

form – The ItemForm instance to arrange.

contributors_tab()[source]#

Build the tab for who made it, in the order they are credited.

Returns:

The contributors tab.

dates()[source]#

Build one date field per CSL date slot, each shown when the type uses it.

An end date is offered for an event, whose dates are often a range, and for any slot that already holds one.

Returns:

The fieldset holding every slot.

helper()[source]#

Return the form helper that draws the whole arrangement.

Returns:

The crispy FormHelper.

holds_value(name)[source]#

Return whether the field already holds something, on this form’s own data.

Parameters:

name – The form field name.

Returns:

True if its value is not empty.

identifiers_tab()[source]#

Build the tab for DOI, ISBN, URL and any other identifier.

Returns:

The identifiers tab.

more_tab()[source]#

Build the tab for notes and the fields most references never need, closed until they are.

Returns:

The more tab.

reference_tab()[source]#

Build the tab for what the reference is, in the order a citation reads it.

Returns:

The reference tab.

section(group)[source]#

Build one item-type section: a fieldset shown when the chosen type uses it.

Parameters:

group – A key of GROUPS.

Returns:

The fieldset.

LEADING_NUMBERING = ('volume', 'issue', 'page', 'number')#

The numbering fields drawn without opening anything; the rarer rest sit under “More numbering”.

SECTION_ORDER = ('container', 'numbering', 'publication', 'original', 'event', 'review', 'legal', 'archive', 'physical')#

the order a citation reads them in.

Type:

The order the item-type sections take on the page

TYPE_GROUPS_FOR_CHOOSING = (('Articles', (ItemType.ARTICLE_JOURNAL, ItemType.ARTICLE_MAGAZINE, ItemType.ARTICLE_NEWSPAPER, ItemType.ARTICLE, ItemType.REVIEW, ItemType.REVIEW_BOOK)), ('Books and reference works', (ItemType.BOOK, ItemType.CHAPTER, ItemType.ENTRY_ENCYCLOPEDIA, ItemType.ENTRY_DICTIONARY, ItemType.ENTRY, ItemType.CLASSIC, ItemType.COLLECTION, ItemType.PAMPHLET, ItemType.PERIODICAL)), ('Conferences and events', (ItemType.PAPER_CONFERENCE, ItemType.SPEECH, ItemType.EVENT, ItemType.PERFORMANCE)), ('Reports and unpublished work', (ItemType.REPORT, ItemType.THESIS, ItemType.STANDARD, ItemType.MANUSCRIPT, ItemType.PERSONAL_COMMUNICATION, ItemType.DOCUMENT)), ('Data and software', (ItemType.DATASET, ItemType.SOFTWARE)), ('Web', (ItemType.WEBPAGE, ItemType.POST_WEBLOG, ItemType.POST)), ('Legal', (ItemType.LEGAL_CASE, ItemType.LEGISLATION, ItemType.BILL, ItemType.REGULATION, ItemType.HEARING, ItemType.TREATY, ItemType.PATENT)), ('Media, images and maps', (ItemType.BROADCAST, ItemType.MOTION_PICTURE, ItemType.INTERVIEW, ItemType.SONG, ItemType.MUSICAL_SCORE, ItemType.FIGURE, ItemType.GRAPHIC, ItemType.MAP)))#

The 45 item types in eight groups a person scans by, not one alphabetical run.

date_field_name(slot, end=False)[source]#

Return the form field name for a date slot’s start, or its end.

Parameters:
  • slot – A DateType value.

  • end – Whether to name the slot’s end date field.

Returns:

The field name, such as date_issued or date_issued_end.

date_shown_when(slot)[source]#

Return the Alpine condition under which a date slot is shown. Published always is.

Parameters:

slot – A DateType value.

Returns:

The condition, as an Alpine expression.

include(template)[source]#

Draw another template in place, with the page’s own context.

Parameters:

template – The template path to include.

Returns:

A crispy HTML element holding the include tag.

role_shown_when(role)[source]#

Return the Alpine condition under which a contributor role’s set is shown. Authors always are.

Parameters:

role – A NameRole value.

Returns:

The condition, as an Alpine expression.

rows_of(names, per_row)[source]#

Lay names out per_row to a row, each in an equal column.

Parameters:
  • names – The field names to place.

  • per_row – How many columns each row holds.

Returns:

The crispy Row objects.

shown_when(group)[source]#

Return the Alpine condition under which an item-type section is shown.

Parameters:

group – A key of GROUPS.

Returns:

The condition, as an Alpine expression.

ConfirmImportForm names nothing the staged file can be found by. The file and the format it was staged as are read from the session, never posted back. Its one hidden field names which preview the page was describing, which is checked against the confirming session’s own value — a page still showing a preview that has since been replaced confirms nothing rather than carrying out the later one. Carrying out a previewed import is a POST protected against cross-site request forgery like any other.

The one write form every create and update flow shares (FS-008, #74).

CONTRIBUTOR_NAMES_DATALIST_ID = 'contributor-names-datalist'#

The id shared by the family-name input’s list= attribute and the page-level <datalist> it references (FS-012, #117), so the two cannot name different ids.

class ConfirmImportForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, bound_field_class=None)[source]#

Bases: Form

Carry out the import a preview described (FS-011, #103).

The staged file’s token and format live in the reader’s own session, so nothing on the page can name someone else’s upload. The one field names which preview the page showed; the view imports only where it matches the session’s value, which stops a stale page from carrying out a later preview.

base_fields = {'preview': <django.forms.fields.CharField object>}#
declared_fields = {'preview': <django.forms.fields.CharField object>}#
property media#

Return all media required to render the widgets on this form.

class CreatableSelect(attrs=None, choices=(), *, placeholder=None, clear_button=None)[source]#

Bases: TomSelect

A Tom Select control that also takes a value typed in, beside the choices it offers.

literature/ui/static/literature/creatable.js turns Tom Select’s create setting on for every select marked data-create, since django-mvp-forms’ widget passes no such setting.

class Media[source]#

Bases: object

js = ['literature/creatable.js']#
build_attrs(base_attrs, extra_attrs=None)[source]#

Mark the select for the script that lets it take typed values.

property media#
class CreatableSelectMultiple(attrs=None, choices=(), *, placeholder=None, clear_button=None, remove_button=None, max_items=None, counted=None, none_text=None, count_text=None)[source]#

Bases: CreatableSelect, TomSelectMultiple

A multiple Tom Select control that takes typed values as tags.

property media#
FORM_FIELDS = ('abstract', 'annote', 'archive', 'archive_collection', 'archive_location', 'archive_place', 'authority', 'call_number', 'chapter_number', 'citation_key', 'collection_number', 'collection_title', 'container_title', 'container_title_short', 'dimensions', 'division', 'edition', 'event_place', 'event_title', 'genre', 'issue', 'journal_abbreviation', 'jurisdiction', 'keyword', 'language', 'medium', 'note', 'number', 'number_of_pages', 'number_of_volumes', 'original_publisher', 'original_publisher_place', 'original_title', 'page', 'page_first', 'part', 'part_title', 'printing', 'publisher', 'publisher_place', 'references', 'reviewed_genre', 'reviewed_title', 'scale', 'section', 'source', 'status', 'supplement', 'title', 'title_short', 'type', 'version', 'volume', 'volume_title', 'volume_title_short')#

Every scalar field of Item except categories, custom, created and modified, built from the field-group mapping so the two cannot drift apart.

class ImportForm(*args, **kwargs)[source]#

Bases: Form

Choose a configured format and a file to run it through (FS-011, #103).

Not a ModelForm: the format resolves the file into entries and items, as the front end has no reading path of its own.

base_fields = {'file': <django.forms.fields.FileField object>, 'format': <django.forms.fields.ChoiceField object>, 'skip_preview': <django.forms.fields.BooleanField object>}#
declared_fields = {'file': <django.forms.fields.FileField object>, 'format': <django.forms.fields.ChoiceField object>, 'skip_preview': <django.forms.fields.BooleanField object>}#
property media#

Return all media required to render the widgets on this form.

class ItemForm(*args, **kwargs)[source]#

Bases: ModelForm

Every scalar field of Item, always, and one date field per CSL date slot.

Scoping by item type is the template’s job: every field is declared, so a group the type does not use is hidden by Alpine but still posts the value it held. Building the field list from the type would blank every omitted field on save.

The model’s help_text records each field’s CSL JSON name, which means nothing to the person filling the form in, so the form carries its own labels and help where the model’s would mislead (FIELD_LABELS, FIELD_HELP). The page’s arrangement is ItemFormLayout’s, built per instance.

Each slot is a start and an end, written to that slot’s ItemDate on save. A slot left empty that was empty stays absent, and a stored date whose only content is unparsed text keeps that text.

class Media[source]#

Bases: object

js = ['literature/item-form.js']#
class Meta[source]#

Bases: object

fields = ('abstract', 'annote', 'archive', 'archive_collection', 'archive_location', 'archive_place', 'authority', 'call_number', 'chapter_number', 'citation_key', 'collection_number', 'collection_title', 'container_title', 'container_title_short', 'dimensions', 'division', 'edition', 'event_place', 'event_title', 'genre', 'issue', 'journal_abbreviation', 'jurisdiction', 'keyword', 'language', 'medium', 'note', 'number', 'number_of_pages', 'number_of_volumes', 'original_publisher', 'original_publisher_place', 'original_title', 'page', 'page_first', 'part', 'part_title', 'printing', 'publisher', 'publisher_place', 'references', 'reviewed_genre', 'reviewed_title', 'scale', 'section', 'source', 'status', 'supplement', 'title', 'title_short', 'type', 'version', 'volume', 'volume_title', 'volume_title_short')#
model#

alias of Item

widgets = {'abstract': <django.forms.widgets.Textarea object>, 'annote': <django.forms.widgets.Textarea object>, 'note': <django.forms.widgets.Textarea object>, 'references': <django.forms.widgets.Textarea object>, 'type': <mvp_forms.widgets.TomSelect object>}#
base_fields = {'abstract': <django.forms.fields.CharField object>, 'annote': <django.forms.fields.CharField object>, 'archive': <django.forms.fields.CharField object>, 'archive_collection': <django.forms.fields.CharField object>, 'archive_location': <django.forms.fields.CharField object>, 'archive_place': <django.forms.fields.CharField object>, 'authority': <django.forms.fields.CharField object>, 'call_number': <django.forms.fields.CharField object>, 'chapter_number': <django.forms.fields.CharField object>, 'citation_key': <django.forms.fields.CharField object>, 'collection_number': <django.forms.fields.CharField object>, 'collection_title': <django.forms.fields.CharField object>, 'container_title': <django.forms.fields.CharField object>, 'container_title_short': <django.forms.fields.CharField object>, 'dimensions': <django.forms.fields.CharField object>, 'division': <django.forms.fields.CharField object>, 'edition': <django.forms.fields.CharField object>, 'event_place': <django.forms.fields.CharField object>, 'event_title': <django.forms.fields.CharField object>, 'genre': <django.forms.fields.CharField object>, 'issue': <django.forms.fields.CharField object>, 'journal_abbreviation': <django.forms.fields.CharField object>, 'jurisdiction': <django.forms.fields.CharField object>, 'keyword': <django.forms.fields.CharField object>, 'language': <django.forms.fields.CharField object>, 'medium': <django.forms.fields.CharField object>, 'note': <django.forms.fields.CharField object>, 'number': <django.forms.fields.CharField object>, 'number_of_pages': <django.forms.fields.CharField object>, 'number_of_volumes': <django.forms.fields.CharField object>, 'original_publisher': <django.forms.fields.CharField object>, 'original_publisher_place': <django.forms.fields.CharField object>, 'original_title': <django.forms.fields.CharField object>, 'page': <django.forms.fields.CharField object>, 'page_first': <django.forms.fields.CharField object>, 'part': <django.forms.fields.CharField object>, 'part_title': <django.forms.fields.CharField object>, 'printing': <django.forms.fields.CharField object>, 'publisher': <django.forms.fields.CharField object>, 'publisher_place': <django.forms.fields.CharField object>, 'references': <django.forms.fields.CharField object>, 'reviewed_genre': <django.forms.fields.CharField object>, 'reviewed_title': <django.forms.fields.CharField object>, 'scale': <django.forms.fields.CharField object>, 'section': <django.forms.fields.CharField object>, 'source': <django.forms.fields.CharField object>, 'status': <django.forms.fields.CharField object>, 'supplement': <django.forms.fields.CharField object>, 'title': <django.forms.fields.CharField object>, 'title_short': <django.forms.fields.CharField object>, 'type': <django.forms.fields.TypedChoiceField object>, 'version': <django.forms.fields.CharField object>, 'volume': <django.forms.fields.CharField object>, 'volume_title': <django.forms.fields.CharField object>, 'volume_title_short': <django.forms.fields.CharField object>}#
clean()[source]#

Check each date slot’s range the way ItemDate does, and report it on the slot.

clean_keyword()[source]#

Join the tags back into one string, or keep the stored string when no keyword changed.

date_slots_holding_values()[source]#

Return the slots with a stored date, of any kind, on the reference being edited.

Returns:

The slot names.

declared_fields = {}#
property media#

Return all media required to render the widgets on this form.

class ItemIdentifierForm(*args, **kwargs)[source]#

Bases: SetPolicedConstraintMixin, ModelForm

An identifier row: one ItemIdentifier in the reference form’s identifiers set (FS-012, #117).

type carries no model-level choices: an unknown kind is stored and left unchecked by design (docs/adr/0002-open-identifier-types.md), so the six known kinds (IdentifierType) are offered through CreatableSelect rather than enforced.

A typed kind matching a known one other than by casing is normalized to its canonical acronym here, so isbn is checked as ISBN. Changing the validator’s dispatch dict instead would also change the import path’s lookups.

Format checking is not this form’s job: ItemIdentifier.clean() calls validate_identifier, which raises a plain ValidationError, so a rejection surfaces as a non-field error.

class Meta[source]#

Bases: object

fields = ('type', 'value')#
help_texts = {'type': '', 'value': ''}#
labels = {'type': 'Identifier type', 'value': 'Identifier'}#
model#

alias of ItemIdentifier

base_fields = {'type': <django.forms.fields.CharField object>, 'value': <django.forms.fields.CharField object>}#
clean_type()[source]#

Normalize a kind matching a known one, other than by casing, to its canonical acronym.

constraint_field: str = 'type'#

A field of the constraint the set polices. Excluding it skips exactly that constraint.

declared_fields = {}#
property media#

Return all media required to render the widgets on this form.

class KeywordsField(*, choices=(), **kwargs)[source]#

Bases: MultipleChoiceField

Keywords as tags, stored as the one comma-separated string CSL JSON keeps them in.

has_changed(initial, data)[source]#

Compare keyword by keyword, so a stored string unchanged in content is unchanged.

prepare_value(value)[source]#

Show a stored string as one tag per keyword.

static split(value)[source]#

Return the keywords a stored string holds, in order.

Parameters:

value – A stored string, or a list of keywords.

Returns:

The keywords. Either a comma or a semicolon ends one, as sources use both.

valid_value(value)[source]#

Accept any keyword: the choices are the catalogue’s own, offered for reuse.

widget = <literature.ui.forms.CreatableSelectMultiple object>#
class NameForm(*args, role=None, **kwargs)[source]#

Bases: ModelForm

A contributor row: an ItemName link whose form also carries its Name (FS-012, #117).

The form declares none of ItemName’s own fields: the role is the set the row sits in, and order arrives through the formset’s can_order field. The name’s parts are unbound fields built from Name’s own via formfield(), and save() turns them into a stored Name. The citation-processor flags (comma_suffix, static_ordering, parse_names) are never declared, so their stored values are preserved.

Parameters:
  • *args – What ModelForm takes.

  • role – The role of the set the row sits in, written onto a new row.

  • **kwargs – What ModelForm takes.

class Meta[source]#

Bases: object

fields = ()#
model#

alias of ItemName

NAME_COPY = {'dropping_particle': ('Particle dropped when sorting', 'Such as van in Ludwig van Beethoven.'), 'family': ('Family name', ''), 'given': ('Given name', ''), 'literal': ('Organisation name', ''), 'non_dropping_particle': ('Particle kept with the family name', 'Such as de in Jean de La Fontaine.'), 'suffix': ('Suffix', 'Such as Jr. or III.')}#

What each name part is called on the page, with an example where the CSL name would leave a person guessing.

NAME_FIELDS = ('family', 'given', 'dropping_particle', 'non_dropping_particle', 'suffix', 'literal')#

The fields that make up a Name, in the order save() compares and writes them.

base_fields = {'dropping_particle': <django.forms.fields.CharField object>, 'family': <django.forms.fields.CharField object>, 'given': <django.forms.fields.CharField object>, 'literal': <django.forms.fields.CharField object>, 'non_dropping_particle': <django.forms.fields.CharField object>, 'suffix': <django.forms.fields.CharField object>}#
clean()[source]#

Require a family name or an unparsed name, unless the row is being deleted.

static create_name(values)[source]#

Create a new, fully validated Name.

Parameters:

values – The name parts, one per NAME_FIELDS.

Returns:

The saved Name.

declared_fields = {'dropping_particle': <django.forms.fields.CharField object>, 'family': <django.forms.fields.CharField object>, 'given': <django.forms.fields.CharField object>, 'literal': <django.forms.fields.CharField object>, 'non_dropping_particle': <django.forms.fields.CharField object>, 'suffix': <django.forms.fields.CharField object>}#
property media#

Return all media required to render the widgets on this form.

save(commit=True)[source]#

Write role onto the link and the name parts onto a Name.

class OpenChoiceField(*, choices=(), **kwargs)[source]#

Bases: ChoiceField

A choice field that also accepts a value outside its choices.

valid_value(value)[source]#

Accept any value: the choices are suggestions.

class SetPolicedConstraintMixin[source]#

Bases: object

Leave one named model constraint to the row’s own formset (FS-012, #117).

A row form validates against the database as it stands, so it cannot see that another row holding the same value is flagged for removal in this submission. A replacement would be refused as a collision. Only the formset can judge the rows being kept, so its clean() performs the check, and the database constraint stays the final backstop.

constraint_field names one field of the constraint rather than the constraint itself: excluding any one of its fields skips exactly that constraint and leaves the others validated.

constraint_field: str#

A field of the constraint the set polices. Excluding it skips exactly that constraint.

validate_constraints()[source]#

Validate model constraints, leaving out the one the formset polices.

class StoredPartialDateField(*, min_resolution='year', max_resolution='day', min_value=None, max_value=None, **kwargs)[source]#

Bases: PartialDateField

A partial date field that shows a stored PartialDate as the text it saves as.

The model hands the form a PartialDate, which never compares equal to the text sent back, so every stored date would count as changed.

prepare_value(value)[source]#

Show a stored partial date as its ISO text.

keyword_choices(own)[source]#

List a reference’s own keywords in stored order, then every other keyword the catalogue uses.

Its own come first because a select sends its options in listed order, and an unchanged save has to send them back in the order they were stored.

Parameters:

own – The reference’s stored keyword string.

Returns:

(word, word) choice pairs.

literature.ui.staging#

StagedUpload holds an uploaded file between a preview and the confirmation that carries it out, since a browser will not re-populate a file input and asking for the file again would defeat the point of previewing. It saves through Django’s storage API, so a project already configuring remote storage gets staging on it without further work, and it names each file by a random token that carries no relationship to the file’s own name or contents.

Four operations: save stages a file and returns its token, open reads it back or returns None where the token names nothing staged, discard removes it once the import it was staged for has run, and sweep removes anything left behind by a preview that was never confirmed. RETENTION_WINDOW is how long an abandoned staging survives a sweep, 24 hours by default.

Which reader staged which file is deliberately not this class’s concern — the token lives in the session, held by the view.

Hold an uploaded file on disk between a preview and its confirmation.

RETENTION_WINDOW = datetime.timedelta(days=1)#

How long a staged file survives an import that never confirmed it, before sweep() removes it: long enough to come back the same working day.

class StagedUpload(storage=None)[source]#

Bases: object

Save, open, discard and sweep a file staged for a later confirm.

Backed by whatever Django’s storage API resolves to (default_storage by default) rather than a hand-built path, so a project already configuring remote storage gets staging on it for free. Every staged file lives under directory, named by a random token that carries no relationship to the file’s own name or contents — the token is only ever useful to whoever was handed it (FS-011, #103). Which reader staged which file is the session’s concern, held by the calling view, never the token’s.

Parameters:

storage – The Django storage to stage on. Defaults to default_storage.

directory = 'literature-imports'#

The storage sub-path staged files are kept under, never the storage root, so a stale token cannot resolve to a project’s own media.

discard(token) → None[source]#

Remove the staged file for token, if it is still there.

Never raises for a token already gone: discarding after a confirm is the ordinary path, so a caller need not check first.

Parameters:

token – The token issued by save().

open(token)[source]#

Open the staged file for reading.

A token nobody issued, or one whose file has been discarded or swept, is indistinguishable here: either way there is nothing to confirm.

Parameters:

token – The token issued by save().

Returns:

A binary file object, or None if token names nothing staged.

save(file) → str[source]#

Stage file and return the token that reads it back.

The token is random (get_random_string, Django’s own CSPRNG-backed helper), never derived from file’s name or content. If the storage backend renames the file to avoid a collision, the token returned is the name it actually used.

Parameters:

file – The uploaded file to stage.

Returns:

The token that reads the file back.

sweep() → None[source]#

Remove every staged file older than RETENTION_WINDOW.

Quietly does nothing if directory does not exist yet — the common case, since it is created lazily by the first save().

literature.ui.importing#

ImportReport turns one ImportResult into what the import report page renders — rows, one ImportReportRow per entry in source order, plus the same created, skipped, failed and total counts the result already carries. ImportReportRow is the frozen row itself: a position numbered from one, the entry’s outcome, its citation key where the source supplies one, its reason where it has one — a failure’s, or a skip’s own reason for what it recognised and set aside — and the URL of the reference it created where it created one.

The import report: turning one ImportResult into what a page renders (FS-011, #103).

class ImportReport(result: ImportResult)[source]#

Bases: object

The front end’s own rendering of one ImportResult.

Wraps the result and exposes rows in source order, plus the same counts the result already carries — this class adds no counting or ordering logic of its own.

Parameters:

result – The import run to render.

property created: int#

How many entries created a reference.

property failed: int#

How many entries failed.

property rows: list[ImportReportRow]#

Every entry the source file held, as one row each, in source order.

property skipped: int#

How many entries were recognised and set aside.

property total: int#

How many entries the source file held.

class ImportReportRow(position: int, outcome: Outcome, citation_key: str | None, reason: str | None, item_url: str | None)[source]#

Bases: object

One rendered row of an import report.

Variables:
  • position (int) – The entry’s place in the source file, counted from one — the report counts from one, the import contract counts from zero.

  • outcome (literature.importers.results.Outcome) – Carried straight through from the EntryResult.

  • citation_key (str | None) – The source’s own handle for the entry, or None — never invented for an entry whose source carried none.

  • reason (str | None) – Why the entry failed, or what was recognised and set aside for one that was skipped, or None where neither applies.

  • item_url (str | None) – The created reference’s own page, or None for an entry that created nothing.

citation_key: str | None#
item_url: str | None#
outcome: Outcome#
position: int#
reason: str | None#

literature.ui.tables#

ItemTable is the catalogue’s table presentation — the columns ItemTableView renders, and the ordering it sorts by.

ImportReportTable renders an import report’s rows. It takes a plain list rather than a queryset, since a report is built from one import’s result and never queried. Its outcome column renders each row’s outcome as a colour-coded badge, created, skipped and failed each their own variant. A created row’s position number links to the reference it produced, and a skipped or failed row’s does not.

The preview builds the same table with per-row attributes, one expression per row naming that row’s outcome, which is what lets the filter above the table hide rows without a request. The one-step report builds it without them, so its rows carry nothing that would need a filter on the page to make sense of.

OutcomeColumn is that column. It is a template column, so the badge is rendered by a template and escaped like any other, rather than built as a marked-safe string in Python. It maps each outcome to its own badge variant and wraps the outcome’s own translated label, which is what the cell carried before it was a badge — the colour is added to the label, never substituted for it. The mapping is a class attribute, VARIANTS, so a project that renders the report itself can subclass the column and map the three outcomes to different variants.

The catalogue as a table (FS-009, #87).

class ContributorsColumn(template_code: str | None = None, template_name: str | None = None, context_object_name: str | None = None, extra_context: dict | Callable[[...], dict] | None = None, **kwargs)[source]#

Bases: TemplateColumn

The credited-names cell.

Selects the values only: the author-role names the view prefetched onto the record as contributors (editor-role names if there are no authors), the first three plus a count of the rest. The template builds the markup, as a name is free text and nothing here is passed through mark_safe. A record with no prefetch degrades to the empty-value marker rather than querying once per row.

get_context_data(record, **kwargs)[source]#

Add the credited names and the hidden-remainder count.

class ImportReportTable(data=None, order_by=None, orderable=None, empty_text=None, exclude=None, attrs=None, row_attrs=None, pinned_row_attrs=None, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template_name=None, default=None, request=None, show_header=None, show_footer=True, extra_columns=None)[source]#

Bases: Table

The import report, one row per entry the format found (FS-011, #103).

Built over a plain list of ImportReportRow, as the report has no model behind it. The position column carries the link because a created row’s citation key may be absent and its position never is.

class Meta[source]#

Bases: object

default = '—'#
empty_text = 'Nothing to show.'#
orderable = False#
template_name = 'django_tables2/bootstrap5-mvp.html'#
base_columns = {'citation_key': <django_tables2.columns.base.Column object>, 'outcome': <literature.ui.tables.OutcomeColumn object>, 'position': <django_tables2.columns.base.Column object>, 'reason': <django_tables2.columns.base.Column object>}#
class IssuedColumn(template_code: str | None = None, template_name: str | None = None, context_object_name: str | None = None, extra_context: dict | Callable[[...], dict] | None = None, **kwargs)[source]#

Bases: TemplateColumn

The issued-date cell.

Picks the issued slot off the record’s prefetched item_dates and hands it to date_value.html, so the precision-and-range rule lives in that one partial.

get_context_data(record, **kwargs)[source]#

Add the record’s own issued date, if it has one.

class ItemTable(data=None, order_by=None, orderable=None, empty_text=None, exclude=None, attrs=None, row_attrs=None, pinned_row_attrs=None, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template_name=None, default=None, request=None, show_header=None, show_footer=True, extra_columns=None)[source]#

Bases: Table

The catalogue, one row per reference.

The contributors and issued cells read two prefetches that ItemTableView.get_queryset() supplies: contributors (author- and editor-role ItemName rows) and item_dates. A view of a consumer’s own must supply them too, or pay one query per row for each.

class Meta[source]#

Bases: object

default = '—'#
empty_text = 'Nothing to show.'#
template_name = 'django_tables2/bootstrap5-mvp.html'#
base_columns = {'citation_key': <django_tables2.columns.base.Column object>, 'container_title': <django_tables2.columns.base.Column object>, 'contributors': <literature.ui.tables.ContributorsColumn object>, 'issued': <literature.ui.tables.IssuedColumn object>, 'title': <django_tables2.columns.base.Column object>, 'type': <django_tables2.columns.base.Column object>}#
order_issued(queryset, is_descending)[source]#

Sort by the issued annotation, undated references last either way.

SQLite and PostgreSQL place NULLs differently, so nulls_last=True is stated in both directions.

Parameters:
  • queryset – The queryset to order.

  • is_descending – Whether the sort is descending.

Returns:

The ordered queryset and True, which tells django-tables2 the queryset is already ordered.

render_title(record)[source]#

Return the first value the reference carries down its title chain.

The chain ends at the citation key, so a title-less reference shows its key rather than an empty-value marker as link text.

Parameters:

record – The Item being rendered.

Returns:

The text for the title cell.

class OutcomeColumn(template_code: str | None = None, template_name: str | None = None, context_object_name: str | None = None, extra_context: dict | Callable[[...], dict] | None = None, **kwargs)[source]#

Bases: TemplateColumn

The outcome cell (FS-011, #103).

Renders django-mvp’s <c-badge> around the outcome’s translated label, so a failed entry is told apart by the word and not only by colour. Skipped is a warning rather than neutral because a skipped entry may carry a reason (docs/adr/0027-a-skipped-entry-may-carry-a-reason.md). The template, not mark_safe, escapes the label.

VARIANTS = {Outcome.CREATED: 'success', Outcome.FAILED: 'error', Outcome.SKIPPED: 'warning'}#
get_context_data(record, **kwargs)[source]#

Add the outcome’s badge variant and its translated label.

Components#

<c-filter> is the outcome filter above the preview’s table. It takes one attribute, outcomes, a sequence of value, label and variant triples, and renders a radio button per outcome plus a reset back to all of them. Choosing one writes the value into outcome on the surrounding scope, which every table row reads to decide whether to show itself, so narrowing the table issues no request and reloads nothing.

The variant is the badge variant that outcome already uses, passed in rather than decided here, so a button and the badges it will leave behind carry the same colour. A project that subclasses OutcomeColumn to remap the outcomes moves the filter with it and cannot end up with the two disagreeing. The reset carries no outcome’s colour, because it names no outcome.

The component opens no scope of its own and wraps itself in no form, both deliberately: it reads and writes the scope the page around it opens, and it has no server to submit to. Anything on a page that reads outcome narrows with it, and the counts the preview renders above it do not read it, which is what keeps them describing the whole file while the table beneath shows part of one.

A project rendering its own import report can use the component the same way, by opening a scope holding outcome and giving its rows something that reads it.