Skip to content

Hives App Reference

The Hives app is the largest app in Bifolk (~6,900 lines), managing the core beekeeping domain: hives, queens, inspections, harvests, honey traceability, and beekeeping operations.

Overview

Location: app/hives/

Purpose: Core beekeeping domain

URL Namespace: hives:

Key Models: Hive, BreedingHive, Queen, HiveInspection, HarvestRecord, HoneyBatch, HoneyBucket, HoneyJar, HivePhoto, HealthStatusChange, BeekeepingOperation (abstract), HiveFeeding, HiveTreatment, HiveMaintenance, HiveCombine, QueenReplacement, OperationPhoto


File Structure

hives/
├── models.py              # 20 models (base + operations + status tracking)
├── mixins.py              # 7 local mixins + 4 re-exported from home.mixins
├── urls.py                # 69 URL patterns
├── signals.py             # 9 signal handlers
├── signals_status.py      # 4 signal handlers (jar + inspection status)
├── views/                 # Views package (9 modules, 3,883 LOC)
│   ├── __init__.py        # Re-exports all views
│   ├── hive_views.py      # Hive CRUD, transfer, labels (770 LOC)
│   ├── queen_views.py     # Queen management, lineage (779 LOC)
│   ├── inspection_views.py # Inspection CRUD + list (284 LOC)
│   ├── harvest_views.py   # Harvest records + reassign (327 LOC)
│   ├── batch_views.py     # Batch/bucket/jar management (723 LOC)
│   ├── combine_views.py   # Hive combination CRUD (264 LOC)
│   ├── photo_views.py     # Photo CRUD (92 LOC)
│   └── operations_views.py # Feeding/treatment/maintenance + PWA API (444 LOC)
├── forms/                 # Forms package (9 files, 46 form classes)
│   ├── __init__.py        # Re-exports all forms
│   ├── base_forms.py      # BaseFilterForm, BaseOperationForm
│   ├── hive_forms.py      # Hive, inspection, and transfer forms
│   ├── queen_forms.py     # Queen CRUD and assignment forms
│   ├── harvest_forms.py   # Harvest create and reassign forms
│   ├── batch_forms.py     # Batch/bucket/jar forms
│   ├── combine_forms.py   # Hive combination forms
│   ├── filter_forms.py    # All filter/report forms
│   └── operation_forms.py # Feeding, treatment, maintenance forms
├── services/
│   ├── __init__.py        # Re-exports
│   ├── batch_service.py   # HoneyBatchService, numbering
│   ├── forecast_service.py # HoneyForecastService
│   ├── geocoding_service.py # Reverse geocoding via Nominatim
│   ├── qrcode_service.py  # QR code generation for labels
│   ├── query_service.py   # Common query patterns
│   └── hive_visualization_service.py # HiveVisualizationService
├── templatetags/
│   ├── hive_tags.py       # can_edit, can_delete, is_breeding_hive filters + render_hive_structure tag
│   └── geocoding_tags.py  # get_address, location_with_address tags
└── templates/hives/       # Templates for all views

Models

See Database Models - Hives App for complete field reference.

Hive

Main hive tracking with location, health status, and GPS coordinates. Hive type (style) comes from ConfigurableChoice (hive_type category).

BreedingHive

Specialized hive for queen breeding (Multi-Table Inheritance from Hive). Displayed with a yellow "Breeding" badge in the unified hive list. Cannot be used in colony splits.

NucleusHive

Nucleus colony (Ableger) classification for colony splits and new colonies (Multi-Table Inheritance from Hive). Displayed with a green "Nucleus" badge in the unified hive list. No special functionality beyond being a distinct classification.

Queen

Queen bee tracking with lineage (self-referencing mother_queen), breed, marking color, origin, and optional breeding record linkage. Marking color follows the international beekeeping standard with fixed choices (White, Yellow, Red, Green, Blue, Unmarked). Supports 5-generation ancestor tracking and lineage graph visualization.

HiveInspection

Inspection records with chamber counts, queen/egg sighting, temperament, disease/pest observations, weight, box count, and optional health status updates for both hive and queen.

Beekeeping Operations

Abstract base (BeekeepingOperation) with common fields: organization, created_by, assigned_to, scheduled/completed dates, status, priority, cost, notes.

Concrete operation types:

  • HiveFeeding — Feed type, quantity, ratio, optional inventory item link
  • HiveTreatment — Treatment type, product, dosage, date, effectiveness
  • HiveMaintenance — Maintenance type, description, parts used
  • HiveCombine — Primary/secondary hive, frames transferred, queen removed, method
  • QueenReplacement — Old/new queen, method, reason, acceptance tracking

Honey Traceability Chain

HarvestRecord → HoneyBatch (Charge) → HoneyBucket → HoneyJar
  • HarvestRecord — Per-hive harvest with weight, frames, honey type
  • HoneyBatch (Charge) — Groups harvests by org/year/honey_type. Identifier: {YEAR}-{TYPE}
  • HoneyBucket — Filled from charge, tracks weight and moisture. Number: {CHARGE}-B{SEQ}
  • HoneyJar — Individual jar from bucket. Number: {BUCKET}-J{SEQ}

Views

Total: 56 views (44 class-based + 12 function-based) across 9 modules

Hive Management (hive_views.py)

View Purpose
HiveListView Unified list (production + breeding + nucleus), filters (org/search/type/health/active), map visualization for hives with GPS coordinates
HiveDetailView Polymorphic detail (Hive, BreedingHive, or NucleusHive), weight trends, harvest forecast, mini-charts (6-month), queen health history, breeding records
HiveCreateView Unified create with production/breeding/nucleus radio selector
HiveUpdateView Polymorphic update, supports converting between production, breeding, and nucleus hive types
HiveDeleteView Polymorphic delete
UserHiveListView Hives created by a specific user
HiveLabelView Printable label with QR code for hive identification
hive_transfer Transfer hive (and queen if present) between organizations (admin/owner required)

Inspection Management (inspection_views.py)

View Purpose
InspectionListView List inspections with sorting and filters (org/hive/date range/queen seen/health status)
InspectionCreateView Create inspection, pre-selects hive/date via query params, supports "Save & Create Next" flow
InspectionDetailView Show inspection details
InspectionUpdateView Update inspection record
InspectionDeleteView Delete inspection record

Harvest Management (harvest_views.py)

View Purpose
HarvestListView List with filters (org/hive/honey type/date range), table actions
HarvestCreateView Create harvest with multi-hive checkbox selection, pre-selects hive via query param
HarvestDetailView Show harvest details and related hives
HarvestUpdateView Update harvest record
HarvestDeleteView Delete harvest record
harvest_reassign Reassign harvest to a different batch (maintains traceability)

Queen Management (queen_views.py)

View Purpose
QueenListView List with filters (org/hive/breed/color/origin/active/has hive/date), statistics
QueenDetailView Details + lineage (3-generation ancestors, daughters), permissions
QueenCreateView Create queen (requires create permission in organization)
QueenUpdateView Update queen
QueenDeleteView Delete queen (prevents deletion if active connections exist)
queen_transfer Transfer queen (and associated hive) to another organization
queen_assign Assign an unassigned queen to a queenless hive
queen_replace Replace a hive's current queen with a different one

Queen Lineage (queen_views.py)

View Purpose
QueenLineageView Single queen's ancestors (5 generations) + daughters + lineage depth
QueenLineageOverview All queens with lineage statistics, filters (org/origin/has mother/marking color)
queen_lineage_graph Interactive network graph template for lineage visualization
queen_lineage_graph_data JSON API endpoint: nodes + edges for vis.js graph (color-coded by marking color)

Hive Combination (combine_views.py)

View Purpose
CombineListView List combinations with filters (org/hive/status/priority/method/date range)
CombineDetailView Show combination details with user permissions
CombineCreateView Create hive combination record
CombineUpdateView Update combination record
CombineDeleteView Delete combination record

Hive Photos (photo_views.py)

View Purpose
HivePhotoCreateView Upload photo to a hive
HivePhotoUpdateView Edit photo caption and primary status
HivePhotoDeleteView Delete photo

Honey Batch System (batch_views.py)

View Purpose
BatchListView List batches with filters (search/honey type/status/date range), sortable columns
BucketListView List all buckets across batches with filters (honey type/status/date range)
BatchDetailView Batch summary, harvest sources, buckets with table actions
BucketDetailView Bucket info, paginated jars, utilization statistics
JarListView List jars with filters (status/honey type), summary statistics
BucketLabelView Printable label with QR code for bucket identification
bucket_create Create bucket from a batch with inventory bucket selection
bucket_create_select_batch Create bucket with batch selection (when batch not preselected)
bucket_return_to_inventory Return empty bucket to warehouse inventory
jar_create Create jar(s) from bucket with inventory jar selection and quantity support
jar_bulk_create Redirects to jar_create (deprecated)

Beekeeping Operations (operations_views.py)

Each operation type (Feeding, Treatment, Maintenance) has 6 views:

  • ListView -- Filtered list with pagination and sorting
  • DetailView -- Full details with photos
  • CreateView -- Standard creation form
  • UpdateView -- Edit form
  • DeleteView -- Deletion with confirmation
  • QuickCreateView -- AJAX creation for quick entry (returns JSON)

All operation views use shared mixins (OperationListMixin, OperationCreateMixin, etc.) for consistent behavior.

PWA Offline API (operations_views.py)

View Purpose
get_hives_for_offline JSON API: simplified hive list (id, name) for offline PWA caching (max 100 hives)

Forms

Location: app/hives/forms/ (9 files, 46 form classes)

Forms are organized into specialized modules for maintainability.

Base Forms (base_forms.py)

Form Type Purpose
BaseFilterForm Form Base class for list filter forms with organization and date range fields
BaseOperationForm ModelForm Base class for operation forms (feeding, treatment, maintenance) with hive filtering

Hive and Inspection Forms (hive_forms.py)

Form Type Purpose
HiveForm ModelForm Create hives with production/breeding/nucleus type selection and dynamic hive style choices
HiveUpdateForm ModelForm Update hives (organization cannot be changed after creation)
BreedingHiveForm ModelForm Create breeding hives (extends HiveForm)
BreedingHiveUpdateForm ModelForm Update breeding hives (extends HiveUpdateForm)
NucleusHiveForm ModelForm Create nucleus hives (extends HiveForm)
NucleusHiveUpdateForm ModelForm Update nucleus hives (extends HiveUpdateForm)
HiveTransferForm Form Transfer a hive between organizations (requires admin/owner in both)
HiveInspectionForm ModelForm Record hive inspections with temperament, health status, and observation fields
HiveInspectionUpdateForm ModelForm Update an existing inspection (hive cannot be changed)
InspectionListFilterForm Form Filter inspections by organization, hive, date range, and health status

Queen Forms (queen_forms.py)

Form Type Purpose
QueenForm ModelForm Create a queen with organization, optional hive, and optional mother queen
QueenUpdateForm ModelForm Update a queen (organization cannot be changed, adds active status)
QueenTransferForm Form Transfer a queen (and its hive) to another organization
QueenAssignForm Form Assign an unassigned queen to a queenless hive
QueenReplaceForm Form Replace a hive's current queen with a different one

Harvest Forms (harvest_forms.py)

Form Type Purpose
HarvestForm ModelForm Create or edit a harvest record with multi-hive selection
HarvestReassignForm Form Reassign a harvest to a different batch

Batch, Bucket, and Jar Forms (batch_forms.py)

Form Type Purpose
BatchCreateForm Form Create a batch from selected harvests (must be same honey type)
BucketCreateForm ModelForm Create a bucket from a batch with weight and moisture validation
BucketCreateWithBatchSelectionForm ModelForm Create a bucket with batch selection dropdown
JarCreateForm Form Create jar(s) from a bucket with inventory jar selection, quantity, and notes fields

Hive Combination Forms (combine_forms.py)

Form Type Purpose
HiveCombineForm ModelForm Create or update a hive combination with method selection
HiveCombineFilterForm Form Filter combination list by organization, hive, status, priority, and method

Operation Forms (operation_forms.py)

Each operation type (Feeding, Treatment, Maintenance) has three forms:

Form Type Purpose
HiveFeedingForm ModelForm Create/update feeding records with feed type and inventory item
FeedingQuickCreateForm ModelForm Minimal form for quick AJAX feeding creation
HiveTreatmentForm ModelForm Create/update treatment records with treatment type and effectiveness
TreatmentQuickCreateForm ModelForm Minimal form for quick AJAX treatment creation
HiveMaintenanceForm ModelForm Create/update maintenance records with maintenance type
MaintenanceQuickCreateForm ModelForm Minimal form for quick AJAX maintenance creation

Filter and Report Forms (filter_forms.py)

Form Purpose
HarvestReportFilterForm Filter harvest reports by date range and hive selection
HealthChangesReportFilterForm Filter health changes with multi-hive comparison
HiveMetricsFilterForm Filter metrics dashboard by date range and hives
HiveListFilterForm Filter hive list by type, style, health status, and active status
QueenListFilterForm Filter queens by breed, marking color, origin, and more
HarvestListFilterForm Filter harvests by organization, hive, honey type, and date
QueenLineageFilterForm Filter lineage overview by origin and marking color
FeedingListFilterForm Filter feeding records by type, status, and priority
TreatmentListFilterForm Filter treatment records by type, effectiveness, and status
MaintenanceListFilterForm Filter maintenance records by type, status, and priority
BatchFilterForm Filter batches by honey type, status, and date range
JarFilterForm Filter jars by status, honey type, and bucket
BucketFilterForm Filter buckets by honey type, status, and date range

View Mixins

Location: app/hives/mixins.py

Four permission and filter mixins are re-exported from home.mixins for backwards compatibility. Seven mixins are defined locally for operation-specific patterns.

Re-exported from home.mixins

Mixin Purpose
OrgCreatePermissionMixin Check user_can_create() for organization-based create permissions
EditPermissionMixin Check user_can_edit() for object-based edit permissions
DeletePermissionMixin Check user_can_delete() for object-based delete permissions
OrgFilterMixin Filter queryset by user's accessible organizations

Local Mixins

Mixin Purpose
OperationCreateMixin Common CreateView pattern: form kwargs, transaction handling, success message
OperationUpdateMixin Common UpdateView pattern: form kwargs, success message
OperationListMixin Common ListView pattern for operations: queryset filtering, sorting, pagination
OperationDetailMixin Common DetailView pattern: permission check, photo context loading
OperationDeleteMixin Common DeleteView pattern: success message handling
OperationQuickCreateMixin AJAX quick-create pattern: JSON response with transaction handling
PolymorphicHiveMixin Try BreedingHive first, then NucleusHive, then fall back to Hive (for multi-table inheritance)

Signals

Signal Trigger Action
track_hive_health_before_save pre_save on Hive Store previous health_status
track_health_status_change post_save on Hive Create HealthStatusChange record
auto_create_batch_for_harvest post_save on HarvestRecord Auto-create batch (if enabled)

Services

HoneyBatchService (services/batch_service.py)

  • create_batch_from_harvests() — Atomic batch creation from multiple harvests
  • create_batch_from_single_harvest() — Convenience wrapper
  • reassign_harvest_to_batch() — Move harvest between batches
  • create_bucket_from_batch() — Create bucket with auto-numbering
  • create_jar_from_bucket() — Create jar with inventory jar tracking and auto-weight calculation
  • get_batch_summary() — Return dict with all batch statistics

HoneyForecastService (services/forecast_service.py)

  • forecast_season_outcome() — Analyze weight gain April-July, project harvest
  • Linear regression for weight trends
  • Confidence levels (low/medium/high)
  • Historical average comparison

HiveVisualizationService (services/hive_visualization_service.py)

  • get_hive_structure(hive) — Query latest inspections for brood chamber and honey super counts
  • Returns structure data (brood chambers, honey supers, stand, last updated date)
  • Brood and honey chamber counts are queried independently (may come from different inspection dates)
  • Used by the render_hive_structure template tag to display a rack-style visualization on the hive detail page

Template Tags

Location: app/hives/templatetags/hive_tags.py

Filter Usage
can_edit {% if hive\|can_edit:user %}
can_delete {% if hive\|can_delete:user %}
is_breeding_hive {% if hive\|is_breeding_hive %}
is_nucleus_hive {% if hive\|is_nucleus_hive %}
render_hive_structure {% render_hive_structure hive %} (inclusion tag)
make_range {% for i in count\|make_range %}

URL Patterns

69 URL patterns covering:

  • Hive CRUD + transfer (8 patterns)
  • Inspections (5 patterns)
  • Harvests + reassignment (6 patterns)
  • Queens + lineage (10 patterns)
  • Queen assign/replace (2 patterns)
  • Hive photos (3 patterns)
  • Honey batches (2 patterns)
  • Buckets (6 patterns)
  • Jars (3 patterns)
  • Feeding operations (6 patterns)
  • Treatment operations (6 patterns)
  • Combines (5 patterns)
  • Maintenance operations (6 patterns)
  • PWA offline API (1 pattern)

See Also