A comprehensive, production-ready Hospital Management System with AI-powered features, multi-role user management, and appointment scheduling. Built with Django REST Framework backend and React.js frontend.
- Technology Stack
- Features
- Project Structure
- Installation & Setup
- Database Setup
- Configuration
- Running the Application
- API Documentation
- User Roles & Permissions
- Deployment
- Framework: Django 4.2.7 + Django REST Framework
- Database: PostgreSQL (core data) + MongoDB (logs & AI interactions)
- Authentication: JWT (JSON Web Tokens)
- File Storage: Local file system (media uploads)
- Framework: React.js 18
- UI Library: Material UI (MUI) 5
- State Management: React Context API
- HTTP Client: Axios
- Routing: React Router v6
- SMS: Twilio
- Email: SendGrid
- Telephony: Twilio, Asterisk (for future AI integration)
- User registration with role-based fields
- JWT-based authentication
- Admin approval system for new users
- Role-based access control (Admin, Doctor, Receptionist, Staff)
- Multi-role registration (Doctor, Staff, Receptionist, Admin)
- Profile picture upload
- Role-specific ID card uploads
- Admin approval/rejection system
- User status management (Pending, Approved, Rejected, Disabled)
- Doctor profiles with specialization
- Availability schedule management
- Time slot management
- Doctor ID card upload
- Create, view, edit, and cancel appointments
- Doctor availability validation
- Prevent double booking
- Appointment status tracking (Pending, Confirmed, Cancelled, Completed)
- Edit restrictions (only before one day of appointment)
- Automatic SMS notifications
- Store call logs in MongoDB
- AI interaction logs
- Call history tracking
- Intent detection and response logging
- Role-based dashboard views
- Statistics (doctors, patients, appointments)
- Today's appointments
- Recent call logs
- Pending approvals (Admin)
- SMS notifications via Twilio
- Email notifications via SendGrid
- In-app notifications stored in MongoDB
- Hospital news broadcast to all users
- Site Settings (Admin only): Change site name, upload logo (shown in corner of all pages, larger size), upload banner image for login/welcome pages. Stored in database (PostgreSQL) and media files.
- Hospital News: Admin can post news; optionally send email to all users. All roles can view news. Admin can delete news.
- Send message to user: Admin can send an email to a specific staff or doctor (select user, subject, message). Uses SendGrid.
- User control: Admin can approve, reject, or disable users (disable stops login; user is not deleted).
AI Project For Hospital/
βββ backend/ # Django Backend
β βββ api/ # Main API app
β β βββ models.py # PostgreSQL models
β β βββ serializers.py # DRF serializers
β β βββ views.py # API views
β β βββ urls.py # URL routing
β β βββ services.py # Business logic
β β βββ permissions.py # Custom permissions
β β βββ mongodb_service.py # MongoDB operations
β βββ hospital_system/ # Django project settings
β β βββ settings.py # Django configuration
β β βββ urls.py # Root URL config
β β βββ wsgi.py # WSGI config
β βββ manage.py # Django management script
β βββ requirements.txt # Python dependencies
β βββ .env # Environment variables
β
βββ src/ # React Frontend
β βββ components/ # Reusable components
β β βββ Layout.jsx # Main layout with sidebar
β βββ pages/ # Page components
β β βββ Login.jsx # Login page
β β βββ Signup.jsx # Registration page
β β βββ Dashboard.jsx # Dashboard
β β βββ Appointments.jsx # Appointment management
β β βββ UserManagement.jsx # User management (Admin)
β β βββ DoctorManagement.jsx # Doctor list
β β βββ CallLogs.jsx # Call logs view
β β βββ Settings.jsx # Site settings - logo, banner (Admin)
β β βββ News.jsx # Hospital news (all view; Admin add/delete)
β β βββ Profile.jsx # User profile
β βββ services/ # API services
β β βββ api.js # Axios API client
β βββ context/ # React Context
β β βββ AuthContext.jsx # Authentication context
β βββ routes/ # Route components
β β βββ ProtectedRoute.jsx # Protected route wrapper
β βββ App.jsx # Main app component
β βββ main.jsx # Entry point
β
βββ package.json # Frontend dependencies
βββ vite.config.js # Vite configuration
βββ .env # Frontend environment variables
βββ README.md # This file
- Python 3.9+
- Node.js 18+ and npm
- PostgreSQL 14+
- MongoDB (Atlas or local instance)
- Git
git clone <repository-url>
cd "AI Project For Hospital"cd backend
python -m venv venv
# Windows
venv\Scripts\activate
# Linux/Mac
source venv/bin/activatepip install -r requirements.txtThe .env file is already created in backend/ directory. Update it with your credentials:
# Update MongoDB password
MONGODB_URI=mongodb+srv://UserName:PASSWORD@rakavan.v2vzewk.mongodb.net/
# Update PostgreSQL credentials if different
DB_PASSWORD=your_postgres_passwordpython manage.py makemigrations
python manage.py migrateOption 1: Using Management Command (Recommended)
python manage.py create_adminThis will create a default admin user with:
- Username:
admin - Email:
admin@hospital.com - Password:
admin123
You can customize these values:
python manage.py create_admin --username myadmin --email myadmin@hospital.com --password mypasswordOption 2: Using Django's createsuperuser
python manage.py createsuperuserFollow the prompts to create an admin account.
# From project root
npm installThe .env file is already created in the root directory with:
VITE_API_BASE_URL=http://localhost:8000/api-
Install PostgreSQL (if not installed)
- Download from: https://www.postgresql.org/download/
- Install with default settings
- Remember the postgres user password
-
Create Database
Option A: Using PowerShell Script (Easiest)
cd backend .\setup_database.ps1
Option B: Using SQL File
cd backend psql -U postgres -f create_database.sql
(Enter password when prompted:
1234based on your .env file)Option C: Manual SQL Command
-- Connect to PostgreSQL psql -U postgres -- (Enter password: 1234) -- Create database CREATE DATABASE hospital_db; \q
Option D: One-line Command
$env:PGPASSWORD='1234'; psql -U postgres -h localhost -c "CREATE DATABASE hospital_db;"
Note: Replace
1234with your actual PostgreSQL password if different. -
Update .env file in
backend/directory:DB_NAME=hospital_db DB_USER=postgres DB_PASSWORD=your_postgres_password DB_HOST=localhost DB_PORT=5432
-
Option A: MongoDB Atlas (Cloud) - Recommended
- Go to https://www.mongodb.com/cloud/atlas
- Create a free cluster
- Create a database user
- Get connection string
- Update
backend/.env:
MONGODB_URI=mongodb+srv://Username:YOUR_PASSWORD@rakavan.v2vzewk.mongodb.net/ MONGODB_DB_NAME=hospital_ai_logs
Replace
YOUR_PASSWORDwith your actual MongoDB password. -
Option B: MongoDB Compass (Local)
- Download MongoDB Compass: https://www.mongodb.com/try/download/compass
- Install and open MongoDB Compass
- Connect to local MongoDB instance (default:
mongodb://localhost:27017) - Create database:
hospital_ai_logs - Update
backend/.env:
MONGODB_URI=mongodb://localhost:27017/ MONGODB_DB_NAME=hospital_ai_logs
Located at: backend/.env
# Django Settings
SECRET_KEY=your-secret-key-here-change-in-production
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1
# PostgreSQL Database
DB_NAME=hospital_db
DB_USER=postgres
DB_PASSWORD=postgres
DB_HOST=localhost
DB_PORT=5432
# MongoDB Connection
MONGODB_URI=mongodb+srv://Username:<db_password>@rakavan.v2vzewk.mongodb.net/
MONGODB_DB_NAME=hospital_ai_logs
# JWT Settings
JWT_SECRET_KEY=your-jwt-secret-key-here
JWT_ALGORITHM=HS256
JWT_EXPIRATION_HOURS=24
# Twilio SMS Settings (Optional - for SMS notifications)
TWILIO_ACCOUNT_SID=your-twilio-account-sid
TWILIO_AUTH_TOKEN=your-twilio-auth-token
TWILIO_PHONE_NUMBER=+1234567890
# Email Settings - SendGrid (Optional - for email notifications)
SENDGRID_API_KEY=your-sendgrid-api-key
EMAIL_FROM=noreply@hospital.com
EMAIL_FROM_NAME=Hospital System
# File Upload Settings
MEDIA_ROOT=media
MAX_UPLOAD_SIZE=5242880Located at: .env (project root)
VITE_API_BASE_URL=http://localhost:8000/apicd backend
python manage.py runserverBackend will run on: http://localhost:8000
# From project root
npm run devFrontend will run on: http://localhost:5173 (or similar port)
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000/api
- Admin Panel: http://localhost:8000/admin
If you used the create_admin management command, use these credentials:
- Username:
admin - Password:
admin123 - Email:
admin@hospital.com
- Frontend Login: http://localhost:5173/login
- Django Admin Panel: http://localhost:8000/admin
If you can't login:
- Make sure you've run migrations:
python manage.py migrate - Verify the admin user exists:
python manage.py create_admin - Check PostgreSQL connection (see Database Setup section)
- Ensure the user status is "Approved" in the database
POST /api/auth/register/
Content-Type: multipart/form-data
Body:
- username: string
- email: string
- password: string
- confirm_password: string
- full_name: string
- date_of_birth: date (YYYY-MM-DD)
- phone_number: string
- address: string
- profile_picture: file (optional)
- about_yourself: string (optional)
- role: string (Doctor, Staff, Receptionist, Admin)
- specialization: string (if role=Doctor)
- doctor_id_card: file (if role=Doctor)
- staff_id_card: file (if role=Staff)
- receptionist_id_card: file (if role=Receptionist)
POST /api/auth/login/
Body:
{
"username": "string",
"password": "string"
}
Response:
{
"access": "jwt_token",
"refresh": "refresh_token",
"user": { ... }
}
GET /api/users/
Authorization: Bearer <token>
GET /api/users/pending/
Authorization: Bearer <token>
POST /api/users/{user_id}/approve/
Authorization: Bearer <token>
Body:
{
"action": "approve" | "reject" | "disable"
}
POST /api/appointments/
Authorization: Bearer <token>
Body:
{
"patient_name": "string",
"patient_age": integer,
"patient_disease": "string",
"contact_number": "string",
"address": "string",
"doctor": "uuid",
"appointment_date": "YYYY-MM-DD",
"appointment_time": "HH:MM:SS"
}
GET /api/appointments/
Authorization: Bearer <token>
POST /api/appointments/{id}/accept/
Authorization: Bearer <token>
GET /api/dashboard/
Authorization: Bearer <token>
Response:
{
"total_doctors": integer,
"total_patients": integer,
"total_appointments": integer,
"today_appointments": integer,
"pending_users": integer,
"recent_calls": [...]
}
GET /api/call-logs/
Authorization: Bearer <token>
Query Params: limit, skip
GET /api/site-settings/
Authorization: Bearer <token>
Returns: { site_name, logo_url, banner_url, ... }
PATCH /api/site-settings/update/
Authorization: Bearer <token> (Admin only)
Content-Type: multipart/form-data
Body: site_name (optional), logo (file), banner (file)
GET /api/hospital-news/list/
Authorization: Bearer <token>
POST /api/hospital-news/create/
Authorization: Bearer <token> (Admin only)
Body: { title, content, send_email_to_all?: boolean }
DELETE /api/hospital-news/<uuid>/delete/
Authorization: Bearer <token> (Admin only)
POST /api/send-message/
Authorization: Bearer <token> (Admin only)
Body: { user_id: uuid, subject: string, message: string }
Or: { email: string, subject: string, message: string }
- Full system access
- Approve/reject user registrations
- Manage all users
- Create and manage appointments
- View all call logs
- Send hospital news to all users
- View dashboard statistics
- View own appointments
- Accept or reject appointments
- Update availability schedule
- View own profile
- Cannot create appointments
- Create appointments
- Edit appointments (before one day)
- View all appointments
- View call logs
- View doctors and patients
- Cannot approve users
- View own profile
- View hospital news
- Limited access (read-only for most features)
id(UUID, Primary Key)username(String, Unique)email(String, Unique)password(Hashed)full_name(String)date_of_birth(Date)phone_number(String)address(Text)profile_picture(Image)about_yourself(Text)role(String: Admin, Doctor, Staff, Receptionist)status(String: Pending, Approved, Rejected, Disabled)date_joined(DateTime)updated_at(DateTime)
id(Primary Key)user_id(Foreign Key β users)doctor_id_card(Image)specialization(String)
id(UUID, Primary Key)patient_name(String)patient_age(Integer)patient_disease(Text)contact_number(String)address(Text)doctor_id(Foreign Key β doctors)appointment_date(Date)appointment_time(Time)booking_time(DateTime)status(String: Pending, Confirmed, Cancelled, Completed)created_by(Foreign Key β users)
{
"caller_number": "string",
"intent": "string",
"response": "string",
"duration": "number",
"status": "string",
"timestamp": "datetime"
}{
"user_id": "string",
"notification_type": "string",
"title": "string",
"message": "string",
"metadata": "object",
"read": "boolean",
"timestamp": "datetime"
}{
"user_id": "string",
"interaction_type": "string",
"input_data": "object",
"output_data": "object",
"metadata": "object",
"timestamp": "datetime"
}-
Set Environment Variables
- Set
DEBUG=False - Update
ALLOWED_HOSTSwith your domain - Use production database credentials
- Set secure
SECRET_KEY
- Set
-
Collect Static Files
python manage.py collectstatic
-
Deploy to platforms like:
- Heroku
- AWS Elastic Beanstalk
- DigitalOcean App Platform
- Railway
-
Build for Production
npm run build
-
Deploy to:
- Vercel
- Netlify
- AWS S3 + CloudFront
- GitHub Pages
-
Update API URL
- Update
VITE_API_BASE_URLin production environment
- Update
- Never commit
.envfiles to version control - Use strong passwords for database users
- Enable HTTPS in production
- Regularly update dependencies
- Use environment variables for all secrets
- Implement rate limiting for API endpoints
- Validate and sanitize all user inputs
curl -X POST http://localhost:8000/api/auth/register/ \
-F "username=drjohn" \
-F "email=drjohn@hospital.com" \
-F "password=SecurePass123" \
-F "confirm_password=SecurePass123" \
-F "full_name=Dr. John Smith" \
-F "date_of_birth=1980-01-15" \
-F "phone_number=+1234567890" \
-F "address=123 Medical St" \
-F "role=Doctor" \
-F "specialization=Cardiology" \
-F "doctor_id_card=@/path/to/id_card.jpg" \
-F "profile_picture=@/path/to/profile.jpg"curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{
"username": "drjohn",
"password": "SecurePass123"
}'curl -X POST http://localhost:8000/api/appointments/ \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
"patient_name": "Jane Doe",
"patient_age": 35,
"patient_disease": "Regular checkup",
"contact_number": "+1234567890",
"address": "456 Patient Ave",
"doctor": "<doctor_uuid>",
"appointment_date": "2024-02-25",
"appointment_time": "10:00:00"
}'If you see errors like:
relation "users" does not existnull value in column "name" of relation "django_content_type"No migrations to applybut tables don't exist
This means the database is corrupted. RESET IT:
- Open pgAdmin
- Right-click
hospital_dbβ Delete/Drop (check "Cascade") - Right-click "Databases" β Create β Database
- Name:
hospital_dbβ Save - Run migrations:
cd backend python manage.py migrate python manage.py create_admin
cd backend
python fix_migrations.py
# Type 'yes' when prompted
python manage.py migrate
python manage.py create_adminSee backend/QUICK_FIX.md for detailed instructions.
-
PostgreSQL Database Does Not Exist
Error:
django.db.utils.OperationalError: database "hospital_db" does not existQuick Fix - Use pgAdmin (Easiest):
- Open pgAdmin (installed with PostgreSQL)
- Connect to PostgreSQL server (password: check your
.envfile, default might be1234) - Right-click "Databases" β Create β Database
- Name:
hospital_db - Click Save
Alternative - Command Line:
# If psql is in PATH $env:PGPASSWORD='1234' # Use your actual password psql -U postgres -h localhost -c "CREATE DATABASE hospital_db;"
Or find psql.exe (usually in
C:\Program Files\PostgreSQL\<version>\bin\):& "C:\Program Files\PostgreSQL\16\bin\psql.exe" -U postgres -h localhost -c "CREATE DATABASE hospital_db;"
See
backend/CREATE_DATABASE_GUIDE.mdfor detailed instructions. -
PostgreSQL Connection Error - "password authentication failed"
Error:
psycopg2.OperationalError: password authentication failed for user "postgres"Solutions:
Option A: Update .env with correct password
# Edit backend/.env file DB_PASSWORD=your_actual_postgres_passwordOption B: Reset PostgreSQL password
-- Connect to PostgreSQL as superuser psql -U postgres -- Change password ALTER USER postgres WITH PASSWORD 'postgres';
Option C: Create a new PostgreSQL user
CREATE USER hospital_user WITH PASSWORD 'your_password'; CREATE DATABASE hospital_db OWNER hospital_user; GRANT ALL PRIVILEGES ON DATABASE hospital_db TO hospital_user;
Then update
backend/.env:DB_USER=hospital_user DB_PASSWORD=your_password
-
Database Connection Error
- Check PostgreSQL is running:
pg_isreadyor check Windows Services - Verify database credentials in
.env - Ensure database exists:
psql -U postgres -l(list databases) - Check PostgreSQL is listening on port 5432
- Check PostgreSQL is running:
-
MongoDB Connection Error
- Verify MongoDB URI in
.env - Replace
<db_password>with actual password - Check network connectivity (for Atlas)
- Ensure database user has proper permissions
- Test connection:
mongosh "your_connection_string"
- Verify MongoDB URI in
-
Migration Errors
- Delete migration files and recreate:
python manage.py makemigrations - Reset database if needed (development only)
- Ensure PostgreSQL is running before migrations
- Delete migration files and recreate:
-
Admin User Creation Issues
- Run:
python manage.py create_admin - If user exists, delete and recreate:
python manage.py shellthenUser.objects.filter(username='admin').delete() - Check user status is "Approved" in database
- Run:
-
API Connection Error
- Verify backend is running on http://localhost:8000
- Check
VITE_API_BASE_URLin.env - Check CORS settings in backend
- Check browser console for CORS errors
-
Login Page Issues
- "Forgot Password" and "Can't access your account?" links are now removed (not implemented)
- Use "Sign Up Here" link to register new accounts
- Admin must approve new registrations before login
-
Build Errors
- Clear
node_modulesand reinstall:rm -rf node_modules && npm install - Check Node.js version (18+)
- Delete
package-lock.jsonand reinstall if needed
- Clear
For issues or questions:
- Check the troubleshooting section
- Review API documentation
- Check Django and React logs
This project is for educational purposes.
Built with β€οΈ for modern healthcare management