Here's a complete Django-based Cow and Bull Management System with:
Models for animals, milk logs, health records, breeding, expenses
Role-based access (admin, manager, vet)
Views and admin panel setup
Basic responsive frontend using Bootstrap
Dashboards with charts and export options
UI available in both English and Bangla
🧱 1. Project Setup
Create Django Project and App:
bash Copy code
django-admin startproject cowbullfarm
cd cowbullfarm
python manage.py startapp farm
python manage.py createsuperuser
Add 'farm', 'crispy_forms', 'django.contrib.humanize' to INSTALLED_APPS.
Install required packages:
bash Copy code
pip install django-crispy-forms matplotlib pandas openpyxl python-dateutil
📦 2. Models (farm/models.py)
python Copy code
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
# Choices
ANIMAL_TYPES = (
('Cow', _('Cow')),
('Bull', _('Bull')),
)
STATUS_CHOICES = (
('Healthy', _('Healthy')),
('Sick', _('Sick')),
('Pregnant', _('Pregnant')),
('Sold', _('Sold')),
)
ROLE_CHOICES = (
('Admin', _('Admin')),
('Manager', _('Manager')),
('Vet', _('Vet')),
)
class Animal(models.Model):
tag_id = models.CharField(max_length=50, unique=True)
breed = models.CharField(max_length=100)
animal_type = models.CharField(max_length=10, choices=ANIMAL_TYPES)
weight = models.FloatField()
status = models.CharField(max_length=20, choices=STATUS_CHOICES)
date_of_birth = models.DateField()
def __str__(self):
return f"{self.tag_id} - {self.animal_type}"
class MilkProduction(models.Model):
animal = models.ForeignKey(Animal, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
quantity_liters = models.FloatField()
def __str__(self):
return f"{self.animal.tag_id} - {self.quantity_liters}L"
class HealthRecord(models.Model):
animal = models.ForeignKey(Animal, on_delete=models.CASCADE)
date = models.DateField()
description = models.TextField()
treatment = models.TextField()
vet = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f"{self.animal.tag_id} - {self.date}"
class BreedingRecord(models.Model):
animal = models.ForeignKey(Animal, on_delete=models.CASCADE)
breeding_date = models.DateField()
expected_calving_date = models.DateField(null=True, blank=True)
outcome = models.TextField(blank=True)
def __str__(self):
return f"{self.animal.tag_id} - {self.breeding_date}"
class Expense(models.Model):
category = models.CharField(max_length=100)
amount = models.FloatField()
description = models.TextField(blank=True)
date = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.category} - {self.amount}"
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(max_length=10, choices=ROLE_CHOICES)
def __str__(self):
return f"{self.user.username} - {self.role}"
Run migrations:
bash Copy code
python manage.py makemigrations
python manage.py migrate
🔐 3. Admin Panel (farm/admin.py)
python Copy code
from django.contrib import admin
from .models import Animal, MilkProduction, HealthRecord, BreedingRecord, Expense, UserProfile
@admin.register(Animal)
class AnimalAdmin(admin.ModelAdmin):
list_display = ['tag_id', 'animal_type', 'breed', 'weight', 'status']
search_fields = ['tag_id']
@admin.register(MilkProduction)
class MilkProductionAdmin(admin.ModelAdmin):
list_display = ['animal', 'date', 'quantity_liters']
@admin.register(HealthRecord)
class HealthRecordAdmin(admin.ModelAdmin):
list_display = ['animal', 'date', 'vet']
@admin.register(BreedingRecord)
class BreedingRecordAdmin(admin.ModelAdmin):
list_display = ['animal', 'breeding_date']
@admin.register(Expense)
class ExpenseAdmin(admin.ModelAdmin):
list_display = ['category', 'amount', 'date']
@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'role']
👤 4. Role-Based Access Middleware
Create a middleware or use @user_passes_test in views.
Example view decorator:
python Copy code
def is_admin(user):
return user.userprofile.role == 'Admin'
def is_manager(user):
return user.userprofile.role in ['Admin', 'Manager']
def is_vet(user):
return user.userprofile.role in ['Admin', 'Vet']
🖥️ 5. Views (farm/views.py)
python Copy code
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, user_passes_test
from .models import Animal, MilkProduction, Expense
from .forms import MilkForm, ExpenseForm
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import pandas as pd
@login_required
def dashboard(request):
milk_data = MilkProduction.objects.all().order_by('-date')[:7]
expense_data = Expense.objects.all().order_by('-date')[:7]
# Chart: Milk Yield
df_milk = pd.DataFrame(list(milk_data.values('date', 'quantity_liters')))
if not df_milk.empty:
df_milk['date'] = pd.to_datetime(df_milk['date'])
df_milk = df_milk.groupby('date')['quantity_liters'].sum().reset_index()
plt.figure(figsize=(8, 4))
plt.plot(df_milk['date'], df_milk['quantity_liters'], marker='o')
plt.title(_('Milk Yield Trend'))
plt.xlabel(_('Date'))
plt.ylabel(_('Liters'))
buf = BytesIO()
plt.savefig(buf, format='png')
plt.close()
chart_milk = base64.b64encode(buf.getvalue()).decode('utf-8')
else:
chart_milk = None
context = {
'milk_data': milk_data,
'expense_data': expense_data,
'chart_milk': chart_milk,
}
return render(request, 'dashboard.html', context)
# Add CRUD views for Milk, Expenses, etc.
📄 6. Templates with Bootstrap
Use {% load i18n %} for multilingual support.
Base Template (templates/base.html)
html Copy code
{% load static %}
<!DOCTYPE html>
<html lang="{{ request.LANGUAGE_CODE }}">
<head>
<meta charset="UTF-8">
<title>Cow & Bull Management</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="{% url 'dashboard' %}">{% trans "Cow & Bull Management" %}</a>
<ul class="navbar-nav ms-auto">
{% if user.is_authenticated %}
<li class="nav-item"><a class="nav-link" href="#">{% trans "Logout" %}</a></li>
{% endif %}
</ul>
</div>
</nav>
<div class="container mt-4">
{% block content %}{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Dashboard (templates/dashboard.html)
html Copy code
{% extends "base.html" %}
{% block content %}
<h2>{% trans "Dashboard" %}</h2>
<div class="row">
<div class="col-md-6">
<h4>{% trans "Milk Production" %}</h4>
<img src="data:image/png;base64,{{ chart_milk }}" class="img-fluid" alt="Milk Chart">
</div>
</div>
{% endblock %}
🌍 7. Internationalization (English + Bangla)
In settings.py:
python Copy code
USE_I18N = True
USE_L10N = True
LANGUAGES = [
('en', _('English')),
('bn', _('Bangla')),
]
LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]
To generate translations:
bash Copy code
django-admin makemessages -l bn
# Edit locale/bn/LC_MESSAGES/django.po
django-admin compilemessages
📥 Export Options
Add CSV export views:
python Copy code
import csv
from django.http import HttpResponse
def export_milk_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="milk.csv"'
writer = csv.writer(response)
writer.writerow(['Date', 'Quantity (L)'])
for milk in MilkProduction.objects.all():
writer.writerow([milk.date, milk.quantity_liters])
return response
Add URL pattern:
python Copy code
path('export/milk/', views.export_milk_csv, name='export_milk'),
📁 8. Static Files and Folders
Structure:
code Copy code
cowbullfarm/
├── templates/
│ └── base.html
│ └── dashboard.html
│ └── animals/
├── static/
│ └── css/
│ └── js/
✅ Final Notes
Features Implemented:
CRUD for Animals, Milk Logs, Health Records, Breeding, Expenses
Role-based access control
Multilingual UI (English & Bangla)
Dashboard with charts using Matplotlib
Export to CSV
Responsive design using Bootstrap
Future Enhancements:
Mobile app integration
SMS/email alerts
Calendar for vet visits
AI prediction for milk yield/health
Would you like me to package this into a downloadable zip or GitHub repo?