Skip to content

feat: implement Django backend aligned with StoryAfrika PRD#3

Open
davidddeveloper wants to merge 6 commits intoproductionfrom
claude/create-storyafrika-prd-E8UVp
Open

feat: implement Django backend aligned with StoryAfrika PRD#3
davidddeveloper wants to merge 6 commits intoproductionfrom
claude/create-storyafrika-prd-E8UVp

Conversation

@davidddeveloper
Copy link
Owner

Summary

This PR implements a complete Django backend for StoryAfrika, transforming the platform from a Flask-based social network into a PRD-compliant cultural preservation platform. The implementation includes all required models, editorial workflow, content organization, and administrative tools.

Key Changes

Backend Architecture (47 files, 3,478 lines)

  • Django 5.2 project with PostgreSQL support and SQLite fallback for development
  • 4 Django apps with clear separation of concerns:
    • users/ - User authentication, writer applications, bookmarks
    • stories/ - Core storytelling with Markdown support and reading analytics
    • taxonomy/ - Content organization (41 countries, 5 categories, 30 themes, 6 eras)
    • editorial/ - Editorial review workflow and homepage curation

Database Models (13+ models)

  • User Management: Custom user model with email auth, writer/editor roles, private bookmarks
  • Story Management: Long-form content with Markdown, auto-HTML conversion, reading time calculation, status workflow (draft → submitted → in_review → approved → published)
  • Editorial Workflow: Story reviews with checklist, revision tracking, internal notes, featured story curation
  • Content Organization: Country, Category, Theme, Era models per PRD taxonomy
  • Analytics: ReadingSession tracking (internal only, not publicly visible)

PRD Compliance

  • Removed social features: No likes, followers, public engagement metrics, comments, or algorithms
  • Editorial-first: Story submission requires review and approval before publication
  • Archive-quality: UUID primary keys, Markdown content, comprehensive audit trails
  • Preservation-focused: Built for long-term cultural significance, not growth hacking

Django Admin Interface

  • Fully configured admin panels for editors to:
    • Manage users and approve writer applications
    • Review stories with editorial checklist
    • Curate homepage with manual positioning
    • Manage taxonomy (countries, categories, themes, eras)
    • View internal analytics

Data Seeding

  • Management command (seed_data) populates initial data:
    • 5 Content Pillars (Categories)
    • 41 African countries with cultural overviews
    • 30 cross-cutting themes
    • 6 historical time periods

Documentation

  • backend/README.md - Comprehensive setup guide and architecture documentation
  • PRD_IMPLEMENTATION.md - Detailed implementation status, roadmap, and architecture decisions
  • .env.example - Configuration template
  • Inline docstrings referencing PRD requirements

Implementation Details

Architecture Decisions

  • Django over Flask: Better ORM for complex relationships, built-in admin, migrations, and REST framework
  • UUID Primary Keys: Future-proof, portable data, no sequential ID leakage
  • Markdown Content: Clean, portable format with sanitization via Bleach
  • Separate Editorial Models: Clear audit trail and internal vs. public data separation

Key Features

  • Reading time calculation (225 words/minute per PRD)
  • Auto-excerpt generation from story content
  • Editorial checklist enforcing cultural sensitivity, originality, completeness, and standards
  • Time-based featured story scheduling (start/end dates)
  • Internal analytics tracking (not exposed publicly)

Next Steps

This Phase 1 completion enables:

  1. Phase 2: Build REST API with DRF serializers and viewsets
  2. Phase 3: Develop Next.js frontend with dark mode, serif typography, and editorial aesthetic
  3. Phase 4: Integration testing and security audit
  4. Phase 5: Production deployment to Fly.io/Railway with managed PostgreSQL

Testing

All models are ready for testing. Django admin is fully functional for manual testing of:

  • Writer application workflow
  • Story submission and review process
  • Editorial approval and publishing
  • Homepage curation

Files Added

  • backend/ directory with complete Django project structure
  • PRD_IMPLEMENTATION.md - Implementation tracking document
  • WORK_SUMMARY.md - Detailed work summary and handoff notes
  • .env.example - Environment configuration template
  • .gitignore - Backend-specific git ignore

https://claude.ai/code/session_0158WUFjcg7CyfzNwUhFfU7g

Complete Django backend implementation following the Product Requirements Document:

## Core Features Implemented

### User Management
- Custom User model with email authentication
- Writer application and approval workflow
- Editor role management
- Private bookmarking system (no public metrics)
- Profile with biography and avatar

### Content Organization (Taxonomy)
- Country-based organization (41 African countries)
- 5 Content Pillars (Categories per PRD)
- 30 cross-cutting Themes
- 6 Historical Eras for time-period tagging
- All with cultural context, no political/economic data

### Story Management
- Long-form storytelling with Markdown support
- Auto-conversion to sanitized HTML
- Reading time calculation (225 words/min)
- Status workflow: draft → submitted → in_review → approved → published
- Rich metadata: category, country, themes, era
- Hero images with captions
- NO engagement metrics (likes, comments, followers)

### Editorial Workflow
- Story submission and review system
- Editorial feedback and revision tracking
- Review checklist for editorial standards
- Story revision history
- Featured story curation for homepage
- Internal editorial notes
- Content guidelines documentation

### Analytics (Internal Only)
- Reading session tracking
- Time spent reading
- Completion rates
- NOT publicly visible (PRD requirement)

## Key PRD Requirements Met

✅ Editorial review required before publication
✅ No social engagement features (likes, followers, comments removed)
✅ Country-based story exploration
✅ Curated homepage (manual, not algorithmic)
✅ Writer application workflow
✅ Archive-quality data models with UUIDs
✅ Content organized by Category, Country, Theme, Era
✅ Reading-focused (no vanity metrics)
✅ Built for long-term preservation

## Technical Implementation

- Django 5.2 with PostgreSQL support (SQLite fallback for dev)
- Django REST Framework ready
- Comprehensive Django Admin for editors
- Migration files for all models
- Seed command for initial data (categories, countries, etc.)
- Email + OAuth authentication support
- Markdown processing with bleach sanitization
- UUID primary keys for portability

## Database Schema

- users: User, WriterApplication, Bookmark
- stories: Story, ReadingSession
- taxonomy: Country, Category, Theme, Era
- editorial: StoryReview, StoryRevision, FeaturedStory, EditorialNote, ContentGuideline

## Next Steps

- [ ] Build Django REST API endpoints
- [ ] Implement Next.js frontend
- [ ] Add Google OAuth integration
- [ ] Create data migration from Flask/MySQL
- [ ] Deploy to production infrastructure

See backend/README.md for full documentation.
Detailed status of PRD implementation covering:
- Completed features (Django backend, models, editorial workflow)
- Remaining work (REST API, Next.js frontend, OAuth)
- Architecture decisions and rationale
- Migration strategy from old Flask platform
- Timeline estimates and testing checklist
- PRD alignment verification

Phase 1 (Django Backend): COMPLETE
Next: REST API + Next.js frontend
Complete summary of Django backend implementation:
- 47 files created, 3,478 lines of code
- All PRD requirements for backend implemented
- 13+ models across 4 Django apps
- Complete Django admin for editors
- Data seeding command
- Comprehensive documentation
- Roadmap for Phases 2-5

Phase 1 Complete: Backend foundation ready for REST API and Next.js frontend.
Complete Django REST Framework API implementation:

## API Features Implemented

### Authentication
- JWT token-based authentication (access + refresh tokens)
- User registration endpoint with automatic token generation
- Login endpoint with email/password
- Token refresh and verify endpoints
- Custom authentication for writers and editors

### API Endpoints

**User Management:**
- POST /api/users/register/ - Register new user
- POST /api/users/login/ - Email/password login
- GET /api/users/me/ - Get current user profile
- GET /api/writers/ - List all approved writers
- GET /api/writers/{username}/ - Writer profile
- POST /api/writer-applications/ - Apply to become writer
- GET /api/writer-applications/ - View applications
- GET/POST/DELETE /api/bookmarks/ - Manage bookmarks

**Stories:**
- GET /api/stories/ - List published stories (paginated)
- POST /api/stories/ - Create story (writers only)
- GET /api/stories/{slug}/ - Story detail
- PUT/PATCH /api/stories/{slug}/ - Update story (author only)
- DELETE /api/stories/{slug}/ - Delete story (author only)
- POST /api/stories/{slug}/submit/ - Submit for review
- GET /api/stories/featured/ - Featured stories
- GET /api/stories/search/?q= - Search stories
- GET /api/stories/{slug}/related/ - Related stories

**Country-Based Discovery:**
- GET /api/countries/ - List all countries
- GET /api/countries/{slug}/ - Country detail
- GET /api/countries/{slug}/stories/ - Stories by country

**Category-Based Discovery:**
- GET /api/categories/ - List all 5 Content Pillars
- GET /api/categories/{slug}/ - Category detail
- GET /api/categories/{slug}/stories/ - Stories by category

**Theme-Based Discovery:**
- GET /api/themes/ - List all themes
- GET /api/themes/{slug}/stories/ - Stories by theme

**Era-Based Discovery:**
- GET /api/eras/ - List all historical eras
- GET /api/eras/{slug}/stories/ - Stories by era

**Editorial:**
- GET /api/featured/ - Currently featured stories
- GET /api/guidelines/ - Content guidelines

**Analytics:**
- POST /api/reading-sessions/ - Track reading sessions

### Serializers Created (13 files)

- **users/serializers.py**: User, Registration, WriterProfile, WriterApplication, Bookmark
- **stories/serializers.py**: StoryList, StoryDetail, StoryCreate, ReadingSession
- **taxonomy/serializers.py**: Country, Category, Theme, Era (with list variants)
- **editorial/serializers.py**: StoryReview, FeaturedStory, ContentGuideline

### ViewSets Created (16 viewsets)

- **users/views.py**: User, Writer, WriterApplication, Bookmark viewsets
- **stories/views.py**: Story, ReadingSession viewsets with custom permissions
- **taxonomy/views.py**: Country, Category, Theme, Era viewsets
- **editorial/views.py**: FeaturedStory, ContentGuideline viewsets

### Custom Permissions

- IsWriterOrReadOnly: Only approved writers can create stories
- IsAuthorOrReadOnly: Only story authors can edit their stories
- Smart querysets: Public sees published, authors see own + published, editors see all

### API Documentation

- Swagger UI at /api/docs/
- ReDoc at /api/redoc/
- OpenAPI schema at /api/schema/
- Comprehensive API_DOCUMENTATION.md with examples

### Admin Personalization

- Custom branding: "StoryAfrika Editorial Dashboard"
- Updated site title and index title
- Disabled "View site" link (Next.js handles frontend)

### Configuration Updates

- Added drf-spectacular for auto-generated API docs
- Added djangorestframework-simplejwt for JWT auth
- Configured SIMPLE_JWT settings (60min access, 7day refresh)
- Configured SPECTACULAR_SETTINGS for API docs
- Updated CORS settings for Next.js frontend
- Updated requirements.txt with new dependencies

## PRD Alignment

✅ Writer-only story creation (application required)
✅ Editorial workflow (submit for review)
✅ Country/Category/Theme/Era based discovery
✅ No public engagement metrics in API
✅ Private bookmarking (no public counts)
✅ Featured stories curated by editors
✅ JWT authentication ready for Next.js
✅ Comprehensive pagination (20 items/page)
✅ Search functionality
✅ Related stories algorithm

## Testing

- ✅ Countries endpoint returns all 41 countries
- ✅ Categories endpoint returns 5 Content Pillars
- ✅ API documentation (Swagger UI) working
- ✅ Pagination working correctly
- ✅ Django check passes with no issues

## Next Steps

- [ ] Build Next.js frontend
- [ ] Integrate Google OAuth
- [ ] Add file upload for hero images
- [ ] Deploy to production

API is fully functional and ready for frontend integration.
Comprehensive summary of REST API implementation covering:
- All 16 viewsets and 13 serializers created
- JWT authentication with token refresh
- 50+ API endpoints
- Interactive API documentation (Swagger UI + ReDoc)
- Custom permissions for writers and editors
- Complete testing results
- Phase 2: COMPLETE ✅
- Added rest_framework_simplejwt.token_blacklist to INSTALLED_APPS
- Fixes 401 authentication errors with JWT tokens
- Created comprehensive Swagger UI testing guide
- Installed missing cryptography dependencies for JWT
- Verified authentication flow working correctly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants