Skip to content

Repository files navigation

KampusAPI - Campus Management Platform

A comprehensive Django REST API for managing various campus activities and services.

📋 Project Overview

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.

🛠️ Technologies & Stack

Backend Framework

  • Django (v5.2.4) - Web framework
  • Django REST Framework - RESTful API development
  • Django Channels - WebSocket support for real-time features

Authentication & Security

  • djangorestframework-simplejwt - JWT (JSON Web Token) authentication
    • Access token lifetime: 1 day
    • Refresh token lifetime: 15 days
    • Automatic token rotation enabled

Database

  • SQLite3 - Database engine
  • Custom user model: KampusUser (extends AbstractUser)

Core Features

  • 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

📁 Application Modules

The project is organized into the following Django apps:

  1. 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
  2. commerce - E-commerce functionality

    • Product management
    • Product sales tracking
  3. community - Community features

    • Community management
    • Community announcements
  4. forum - Discussion forum

    • Forum entries and discussions
    • Like/voting system
  5. jobs - Job postings and listings

    • Job advertisements
    • Employment opportunities
  6. job_intern - Internship management

    • Internship postings
    • Intern place management
  7. chat - Real-time messaging

    • User-to-user communication via WebSocket
  8. lost_and_find_items - Lost & Found service

    • Lost item reporting
    • Found item tracking

🏗️ Architecture & Code Structure

Serializers

The project uses Django REST Framework Serializers for data validation and transformation:

Accounts Module

  • 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

Commerce Module

  • 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

Forum Module

  • EntrySerializer - Forum discussion entries
  • EntryCommentSerializer - Comments on forum entries
  • EntryLikeSerializer - Like/voting system with custom update (no-op)
  • TopicSerializer - Forum topics

Community Module

  • CommunitySerializer - Community management
  • CommunityAnnouncementSerializer - Community announcements
    • Blocked fields in updates: announcement_community (cannot change parent community)

Internship Module

  • InternPlaceSerializer - Internship locations
  • InternAnnouncementSerializer - Internship job postings
  • InternCategorySerializer - Internship categorization

Lost & Found Module

  • ItemSerializer - Lost/found item tracking

Jobs Module

  • DiscountAnnouncementSerializer - Job/discount announcements

Permissions System

Custom permission classes defined in accounts/permissions.py:

IsAdmin

  • Requires: Admin user + authenticated
  • Message: "Only Admin can reach this page."

IsStudent

  • Allows: Students and Admins
  • Message: "Permission Denied."

IsCommAgent

  • Requires: Community Agent + authenticated
  • Message: "Only Community Agents can reach this page"

IsStudentOrCommAgent

  • Allows: Students, Community Agents, and Admins
  • Message: "You must be either a student or a comm agent."

Helper Methods

Located in core/helpers.py, these utility functions standardize common operations:

*serializer_saver(serializer_class, instance, data, , context=None, partial=False)

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
)

*validate_image(image, , min_h, min_w, max_h, max_w)

Image dimension validation:

  • Opens image using PIL (Python Imaging Library)
  • Validates height constraints: min_h to max_h
  • Validates width constraints: min_w to max_w
  • Raises ValidationError with descriptive messages
  • Used by ProfilePictureValidationSerializer

update_field(self, request, pk, data, ErrorName, Error)

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

get_related_field(self, serializer_class, related_name, ErrorName, Error, pk=None)

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.)

View Patterns

The project uses ViewSets with custom actions:

UserViewSet Example

- 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 entries

Custom actions use the helper functions for DRY (Don't Repeat Yourself) code.

ProductCategoryViewSet

- list() - All product categories
- retrieve(pk) - Single category
- create() - Create new category
- @action get_products(pk) - Get all products in category

ProductViewSet

- list() - All products
- retrieve(pk) - Single product
- create() - Create new product
- update(pk) - Update product
- @action sold(pk) - Mark product as sold (PUT request)

API Request/Response Flow

  1. Request → Authentication check (JWT token)
  2. Authorization → Permission class validation
  3. Validation → Serializer validates input data
  4. Processing → Helper methods execute business logic
  5. 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"
  }'

🚀 Getting Started

Prerequisites

  • Python 3.x
  • pip (Python package manager)
  • Pillow (PIL) - for image processing

Installation

  1. Clone the repository:
git clone <repository-url>
cd kampusApi
  1. Install required dependencies:
pip install django==5.2.4 djangorestframework djangorestframework-simplejwt channels pillow
  1. Apply database migrations:
python manage.py migrate
  1. Create a superuser:
python manage.py createsuperuser
  1. Run the development server:
python manage.py runserver

The API will be available at http://localhost:8000

🔐 Authentication

The API uses JWT (JSON Web Token) authentication. To authenticate:

  1. Obtain tokens via the login endpoint
  2. Include the access token in the Authorization header:
Authorization: Bearer <access_token>

📂 Media Files

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

⚙️ Configuration

REST Framework Settings

  • Default pagination: 10 items per page
  • Trailing slash: Disabled
  • Default permission: Authenticated users only
  • Authentication: JWT token required

Database

  • Engine: SQLite3
  • File: db.sqlite3

🗄️ Custom User Model

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 path
  • Phone_Number - Contact phone number (max 20 chars, optional)
  • Faculty - User's faculty (optional)
  • Department - User's department (optional)
  • Role - User type with choices:
    • Admin - Administrator
    • Student - Regular student (default)
    • comm_agent - Community agent

Role Properties

  • is_student - Returns True if Role == 'Student'
  • is_admin - Returns True if Role == 'Admin'
  • is_comm_agent - Returns True if Role == 'comm_agent'

Custom User Manager (KampusUserManager)

  • create_user() - Creates regular user with Username, StudentID, Role, and password
  • create_superuser() - Creates admin user with is_staff and is_superuser flags
  • Validates required fields before creation

📊 Database Models & Relationships

Accounts Module

  • KampusUser (Custom User Model)
    • Properties: is_student, is_admin, is_comm_agent
    • Relations: One-to-many with products, entries, likes, comments

Commerce Module

  • 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}
  • ProductCategory

    • Fields: category_name (unique)
  • ProductStatus

    • Fields: status (unique)

Forum Module

  • 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}
  • 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)
  • 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)

Community Module

  • Community

    • Manages community groups
  • CommunityAnnouncement

    • Foreign Key: announcement_community (Community)
    • Related announcements for communities

Internship Module

  • InternPlace - Internship locations
  • InternCategory - Internship types
  • InternAnnouncement - Internship job postings

Lost & Found Module

  • Item - Lost or found items

Jobs Module

  • DiscountAnnouncement - Job and discount announcements

🔗 API Relationships

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

🛡️ Security Features

  • 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

📚 Additional Resources


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.

About

for hackathon

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages