A comprehensive Django REST API for managing various campus activities and services.
KampusAPI is a multi-module Django REST Framework application designed to handle various campus-related functionalities including user management, commerce, community features, forums, job postings, internships, and lost & found items management.
- Django (v5.2.4) - Web framework
- Django REST Framework - RESTful API development
- Django Channels - WebSocket support for real-time features
- djangorestframework-simplejwt - JWT (JSON Web Token) authentication
- Access token lifetime: 1 day
- Refresh token lifetime: 15 days
- Automatic token rotation enabled
- SQLite3 - Database engine
- Custom user model:
KampusUser(extends AbstractUser)
- Pagination - Page-based pagination (10 items per page)
- Permissions - Token-based authentication required by default
- Media Handling - Image upload support for profile pictures and other media files
The project is organized into the following Django apps:
-
accounts - User management and authentication
- Custom user model with role-based access (Admin, Student, Community Agent)
- Profile picture upload
- User phone number and department tracking
-
commerce - E-commerce functionality
- Product management
- Product sales tracking
-
community - Community features
- Community management
- Community announcements
-
forum - Discussion forum
- Forum entries and discussions
- Like/voting system
-
jobs - Job postings and listings
- Job advertisements
- Employment opportunities
-
job_intern - Internship management
- Internship postings
- Intern place management
-
chat - Real-time messaging
- User-to-user communication via WebSocket
-
lost_and_find_items - Lost & Found service
- Lost item reporting
- Found item tracking
The project uses Django REST Framework Serializers for data validation and transformation:
-
UserSerializer - Handles user registration and basic user data
- Validates profile picture dimensions (500x500 to 1000x1000px)
- Custom password validation
- Required fields: Username, StudentID, Password, Role
- Custom error messages for validation
-
MeSerializer - Self-user management endpoint
- Allows users to update their own profile
- Fields: Username, first_name, last_name, email, password, Profile_Picture, Phone_Number
- Role is read-only (cannot be self-modified)
- Supports password updates
-
ProfilePictureValidationSerializer - Base class for image validation
- Validates image height and width constraints
- Uses PIL for image processing
-
ProductSerializer - Product management
- Fields: All product fields (auto-generated from model)
- Custom update logic with blocked fields:
product_user,product_date - Prevents modification of user ownership and creation date
-
ProductCategorySerializer - Product categorization
- EntrySerializer - Forum discussion entries
- EntryCommentSerializer - Comments on forum entries
- EntryLikeSerializer - Like/voting system with custom update (no-op)
- TopicSerializer - Forum topics
- CommunitySerializer - Community management
- CommunityAnnouncementSerializer - Community announcements
- Blocked fields in updates:
announcement_community(cannot change parent community)
- Blocked fields in updates:
- InternPlaceSerializer - Internship locations
- InternAnnouncementSerializer - Internship job postings
- InternCategorySerializer - Internship categorization
- ItemSerializer - Lost/found item tracking
- DiscountAnnouncementSerializer - Job/discount announcements
Custom permission classes defined in accounts/permissions.py:
- Requires: Admin user + authenticated
- Message: "Only Admin can reach this page."
- Allows: Students and Admins
- Message: "Permission Denied."
- Requires: Community Agent + authenticated
- Message: "Only Community Agents can reach this page"
- Allows: Students, Community Agents, and Admins
- Message: "You must be either a student or a comm agent."
Located in core/helpers.py, these utility functions standardize common operations:
Unified serializer saving logic:
- Instantiates serializer with provided data
- Runs validation with
raise_exception=True - Returns validated and saved serializer
- Reduces code duplication across views
serializer = serializer_saver(
serializer_class=UserSerializer,
instance=user,
data=request.data,
partial=True
)Image dimension validation:
- Opens image using PIL (Python Imaging Library)
- Validates height constraints:
min_htomax_h - Validates width constraints:
min_wtomax_w - Raises
ValidationErrorwith descriptive messages - Used by ProfilePictureValidationSerializer
Generic field update endpoint:
- Fetches object by primary key with 404 handling
- Validates and saves using
serializer_saver - Returns standardized error responses
- Used for partial updates like role changes
Fetch related object collections:
- Retrieves parent object by pk
- Accesses related field using
getattr - Serializes many related objects
- Returns 404 error if object not found
- Used for nested resources (user products, entries, etc.)
The project uses ViewSets with custom actions:
- list() - All users (admin only)
- retrieve(pk) - Single user details
- update(pk) - Update user by pk
- create() - Register new user
- @action me - Get/update current user
- @action change_role(pk) - Change user role (admin only)
- @action products(pk) - Get user's products
- @action entries(pk) - Get user's forum entries
- @action entry_likes(pk) - Get user's liked entriesCustom actions use the helper functions for DRY (Don't Repeat Yourself) code.
- list() - All product categories
- retrieve(pk) - Single category
- create() - Create new category
- @action get_products(pk) - Get all products in category- list() - All products
- retrieve(pk) - Single product
- create() - Create new product
- update(pk) - Update product
- @action sold(pk) - Mark product as sold (PUT request)- Request → Authentication check (JWT token)
- Authorization → Permission class validation
- Validation → Serializer validates input data
- Processing → Helper methods execute business logic
- Response → Serialized data returned to client
Example request:
curl -X POST http://localhost:8000/api/users/ \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"Username": "john_doe",
"StudentID": "2024001",
"email": "john@campus.edu",
"password": "secure_password",
"Role": "Student"
}'- Python 3.x
- pip (Python package manager)
- Pillow (PIL) - for image processing
- Clone the repository:
git clone <repository-url>
cd kampusApi- Install required dependencies:
pip install django==5.2.4 djangorestframework djangorestframework-simplejwt channels pillow- Apply database migrations:
python manage.py migrate- Create a superuser:
python manage.py createsuperuser- Run the development server:
python manage.py runserverThe API will be available at http://localhost:8000
The API uses JWT (JSON Web Token) authentication. To authenticate:
- Obtain tokens via the login endpoint
- Include the access token in the Authorization header:
Authorization: Bearer <access_token>
The project handles media uploads organized in these directories:
/media/profile_pictures/- User profile pictures/media/communities/- Community-related images/media/products/- Commerce product images/media/intern/- Internship-related images
- Default pagination: 10 items per page
- Trailing slash: Disabled
- Default permission: Authenticated users only
- Authentication: JWT token required
- Engine: SQLite3
- File:
db.sqlite3
KampusUser extends Django's AbstractUser with:
Username- Unique username field (max 20 chars)StudentID- Unique student identifier (max 50 chars)Profile_Picture- User profile image with custom upload pathPhone_Number- Contact phone number (max 20 chars, optional)Faculty- User's faculty (optional)Department- User's department (optional)Role- User type with choices:Admin- AdministratorStudent- Regular student (default)comm_agent- Community agent
is_student- Returns True if Role == 'Student'is_admin- Returns True if Role == 'Admin'is_comm_agent- Returns True if Role == 'comm_agent'
create_user()- Creates regular user with Username, StudentID, Role, and passwordcreate_superuser()- Creates admin user with is_staff and is_superuser flags- Validates required fields before creation
- KampusUser (Custom User Model)
- Properties: is_student, is_admin, is_comm_agent
- Relations: One-to-many with products, entries, likes, comments
-
Product
- Foreign Key:
product_user(KampusUser) - related_name: 'products' - Foreign Key:
product_category(ProductCategory) - related_name: 'products' - Foreign Key:
product_status(ProductStatus) - related_name: 'products' - Fields: title, price, description, image, date (auto), sold (boolean)
- Image upload path:
products/images/{id}-{filename}
- Foreign Key:
-
ProductCategory
- Fields: category_name (unique)
-
ProductStatus
- Fields: status (unique)
-
Entry (Forum Discussion Post)
- Foreign Key:
entry_user(KampusUser) - related_name: 'entries' - Foreign Key:
entry_topic(Topic) - related_name: 'entries' - Fields: title, text, image (optional), date (auto)
- Image upload path:
forum/entry_images/{filename}
- Foreign Key:
-
Topic
- Fields: topic_name (unique)
-
EntryLike (Voting System)
- Foreign Key:
liked_user(KampusUser) - related_name: 'likes' - Foreign Key:
liked_entry(Entry) - related_name: 'likes' - Fields: date (auto)
- Foreign Key:
-
EntryComment (Replies to Entries)
- Foreign Key:
comment_entry(Entry) - related_name: 'comments' - Foreign Key:
comment_user(KampusUser) - related_name: 'comments' - Fields: comment_text (max 1000 chars)
- Foreign Key:
-
Community
- Manages community groups
-
CommunityAnnouncement
- Foreign Key:
announcement_community(Community) - Related announcements for communities
- Foreign Key:
- InternPlace - Internship locations
- InternCategory - Internship types
- InternAnnouncement - Internship job postings
- Item - Lost or found items
- DiscountAnnouncement - Job and discount announcements
Example URL patterns for nested resources:
GET /api/users/{id}/products/ - User's products
GET /api/users/{id}/entries/ - User's forum entries
GET /api/users/{id}/entry_likes/ - User's liked entries
GET /api/product-categories/{id}/get_products/ - Category's products
- JWT Authentication - Token-based API access
- Permission Classes - Role-based access control (Admin, Student, CommAgent)
- Image Validation - Dimension and size constraints for uploads
- Password Hashing - Using Django's built-in password hashing
- CSRF Protection - Middleware enabled for form submissions
- Django Documentation: https://docs.djangoproject.com/
- Django REST Framework: https://www.django-rest-framework.org/
- Django Channels: https://channels.readthedocs.io/
- JWT Authentication: https://django-rest-framework-simplejwt.readthedocs.io/
Project Information:
- Current Branch: main
- Repository: kampusApp by muratyl2k4
Note: This is a development project with DEBUG mode enabled. Ensure proper security configurations before deploying to production.