Maqsad: RESTful API asosida professional vazifalarni boshqarish tizimini yaratish
ToDo API - bu Django REST Framework bilan qurilgan kuchli REST API, foydalanuvchilarga vazifalar (tasks) yaratish, o'qish, yangilash va o'chirish (CRUD) imkoniyatini beradi. Tizim JWT autentifikatsiya, PostgreSQL database va role-based access control bilan qurilgan.
-
π JWT Authentication
- Secure token-based authentication
- Access va Refresh tokens
- Token lifecycle management
-
π Task Management
- CRUD operations (Create, Read, Update, Delete)
- Task status tracking (Completed/Pending)
- Public/Private task visibility
- Task filtering va searching
-
π€ User Management
- Custom user model
- User profiles
- Role-based permissions
-
π Advanced Filtering
- Search by task title
- Filter by status (completed/pending)
- Filter by visibility (public/private)
- Ordering by date
-
π API Documentation
- Swagger UI (drf-yasg)
- ReDoc documentation
- OpenAPI 3.0 schema
-
β‘ Performance
- Database indexing
- Query optimization
- Pagination support
- Celery async tasks
- Framework: Django 5.1
- API: Django REST Framework
- Database: PostgreSQL 12+
- Authentication: JWT (djangorestframework-simplejwt)
- API Documentation: drf-yasg (Swagger/ReDoc)
- Task Queue: Celery + Celery Beat
- Configuration: python-decouple
- django-filter - Advanced filtering
- psycopg2-binary - PostgreSQL adapter
- redis - Cache & message broker
ToDoAPILevelUp/
βββ config/ # Django settings
β βββ settings.py # Asosiy sozlamalar
β βββ urls.py # URL routing
β βββ asgi.py # ASGI config
β βββ wsgi.py # WSGI config
βββ todo/ # Task app (Main)
β βββ models.py # Task model
β βββ views.py # APIViews
β βββ serializers.py # DRF serializers
β βββ filters.py # Custom filters
β βββ permissions.py # Permission classes
β βββ urls.py # Todo URLs
β βββ tasks.py # Celery tasks
βββ accounts/ # User authentication
β βββ models.py # CustomUser model
β βββ views.py # Auth endpoints
β βββ serializers.py # User serializers
β βββ urls.py
βββ common/ # Shared utilities
β βββ models.py # Common models
β βββ permissions.py # Common permissions
β βββ utils.py # Helper functions
βββ templates/ # Email templates
βββ requirements.txt # Dependencies
βββ manage.py # Django CLI
βββ README.md
- Python 3.9+
- PostgreSQL 12+
- Redis (optional, but recommended)
- pip/venv
# Virtual environment yaratish
python -m venv venv
# Activate
source venv/bin/activate # Linux/Mac
# yoki
venv\Scripts\activate # Windowspip install -r requirements.txt.env.example faylini .env ga nomi o'zgarting:
cp .env.example .env.env faylini tahrirlang:
SECRET_KEY=your-secret-key-change-this-in-production
DEBUG=True
POSTGRES_HOST=localhost
POSTGRES_DB=todo_api
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_PORT=5432
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/1# Migrations yaratish
python manage.py makemigrations
# Migrations qo'llash
python manage.py migrate
# Superuser yaratish (admin uchun)
python manage.py createsuperuserpython manage.py runserverServer http://localhost:8000 da ishga tushadi
- Swagger UI: http://localhost:8000/api/schema/swagger/
- ReDoc: http://localhost:8000/api/schema/redoc/
- Admin Panel: http://localhost:8000/admin/
POST /api/accounts/register/ # Yangi account
POST /api/accounts/login/ # Login (username + password)
POST /api/accounts/token/ # JWT tokens olish
POST /api/accounts/token/refresh/ # Token refresh
GET /api/accounts/profile/ # Mening profilim
GET /api/todos/ # Barcha tasks (paginated)
POST /api/todos/ # Yangi task yaratish
GET /api/todos/<id>/ # Task details
PUT /api/todos/<id>/ # Task update
PATCH /api/todos/<id>/ # Partial update
DELETE /api/todos/<id>/ # Task o'chirish
GET /api/todos/?q=search_term # Search by title
GET /api/todos/?completed=true # Filter by status
GET /api/todos/?is_public=false # Filter by visibility
GET /api/todos/?ordering=-created_at # Sorting
1. POST /api/accounts/token/
{
"username": "user",
"password": "pass"
}
Response:
{
"access": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGc..."
}
2. Header bilan request:
Authorization: Bearer <access_token>
- Access Token: 60 daqiqa
- Refresh Token: 1 kun
class Task(models.Model):
user - ForeignKey to User
title - CharField(max_length=200)
description - TextField
completed - BooleanField (default=False)
is_public - BooleanField (default=False)
created_at - DateTimeField (auto_now_add=True)
updated_at - DateTimeField (auto_now=True)- about property - title + description birlashtiradi
Fayl: todo/models.py (13-qator)
# β NOTO'G'RI:
discription = models.TextField()
# β
TO'G'RI:
description = models.TextField()Sababi: Python naming conventions va database schema uchun "description" to'g'ri yozuv.
Ta'siri:
- Database sxemasida "discription" deb saqlanadi
- API response-da "discription" bo'ladi
- Serializerlarni moslashtirishga to'g'ri keladi
Fix qilish:
- Migration yaratish kerak:
python manage.py makemigrations todo
python manage.py migrate- Serializer-da field nomini o'zgartirish:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ['id', 'title', 'description', 'completed', 'is_public']Fayl: config/settings.py (147-148 qatorlar)
# β XAVFSIZ EMAS:
EMAIL_HOST_USER = "azizbeknuraliyev2005@gmail.com"
EMAIL_HOST_PASSWORD = "cykj mxum fmvv jejo"
# β
XAVFSIZ:
EMAIL_HOST_USER = config("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD")Sababi: Credentials GitHub-da ochiq ko'rinmoqda!
Xavfsizlik tahdidlari:
- Parol bukanlanishi mumkin
- Spam emaillar jo'natilishi mumkin
- Account compromised bo'lishi mumkin
To'g'rilash:
.envfaylga qo'shish:
EMAIL_HOST_USER=azizbeknuraliyev2005@gmail.com
EMAIL_HOST_PASSWORD=your_app_password- Settings.py-da:
EMAIL_HOST_USER = config("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD").gitignorega.envqo'shish (agar qo'shilmagan bo'lsa):
.env
.env.local
*.pyc
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': 'localhost',
'NAME': 'todo_api',
'PORT': 5432,
'USER': 'postgres',
'PASSWORD': 'your_password',
}
}REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
],
}SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}python manage.py test todo
# Verbosity bilan
python manage.py test todo -v 2
# Specific test
python manage.py test todo.tests.TaskTestCasecurl -X POST http://localhost:8000/api/todos/ \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Ishni bajarib bo\'lish",
"description": "Urgent task",
"completed": false,
"is_public": true
}'curl -X GET http://localhost:8000/api/todos/?completed=false \
-H "Authorization: Bearer YOUR_TOKEN"curl -X PATCH http://localhost:8000/api/todos/1/ \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"completed": true}'# settings.py
DEBUG = True
INTERNAL_IPS = ['127.0.0.1', 'localhost']LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': 'error.log',
},
},
}python manage.py check --deploypython manage.py collectstatic --noinputDEBUG=False
SECRET_KEY=your-very-secure-key
ALLOWED_HOSTS=yourdomain.com,api.yourdomain.com
DATABASE_URL=postgresql://user:pass@host:port/dbnamefirdavsDev - Asosiy Developer
MIT License - Batafsil ma'lumot uchun LICENSE faylini ko'ring
Last Updated: 2026-04-23 Status: β Production Ready