Django Integration

Full-stack astrology with Django

Setup

# Python 3.10+; credentials stay in the server environment
pip install 'Django>=5.2,<6' djangorestframework vedika-sdk django-environ celery
django-admin startproject astrology_project
cd astrology_project
python manage.py startapp charts
# After creating the files below:
python manage.py makemigrations charts
python manage.py migrate

Settings Configuration

# settings.py — additions to generated settings
import environ
env = environ.Env()
environ.Env.read_env()
VEDIKA_API_KEY = env('VEDIKA_API_KEY')
INSTALLED_APPS += ['rest_framework', 'charts']
USE_TZ = True
CELERY_BROKER_URL = env('CELERY_BROKER_URL')  # Your existing approved broker

Models

# charts/models.py
from django.db import models
from django.contrib.auth.models import User

class BirthProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    datetime = models.DateTimeField()
    latitude = models.DecimalField(max_digits=9, decimal_places=6)
    longitude = models.DecimalField(max_digits=9, decimal_places=6)
    timezone = models.CharField(max_length=50, blank=False)

    # Cached chart data
    sun_sign = models.CharField(max_length=20, blank=True)
    moon_sign = models.CharField(max_length=20, blank=True)
    ascendant = models.CharField(max_length=20, blank=True)
    chart_data = models.JSONField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} - {self.sun_sign}"

# charts/serializers.py — separate file
from rest_framework import serializers
from .models import BirthProfile
from .services import birth_input, birth_values

class BirthProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = BirthProfile
        fields = ['id', 'name', 'datetime', 'latitude', 'longitude', 'timezone',
                  'sun_sign', 'moon_sign', 'ascendant', 'chart_data']
        read_only_fields = ['id', 'sun_sign', 'moon_sign', 'ascendant', 'chart_data']

    def validate(self, attrs):
        values = birth_values(self.instance) if self.instance else {}
        values.update(attrs)
        if 'datetime' in self.initial_data:
            values['datetime'] = self.initial_data['datetime']
        try:
            birth_input(values)
        except (ValueError, TypeError):
            raise serializers.ValidationError('Explicit valid birth inputs required') from None
        return attrs

Vedika Service

# charts/services.py
import math
import re
from datetime import date, datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.conf import settings
from vedika import VedikaClient
from vedika.exceptions import VedikaAPIError

def coordinate(value, limit):
    if value is None or isinstance(value, bool):
        raise ValueError('Coordinate required')
    number = float(value)
    if not math.isfinite(number) or abs(number) > limit:
        raise ValueError('Invalid coordinate')
    return number

def birth_input(value):
    stamp, zone = value.get('datetime'), value.get('timezone')
    if not isinstance(stamp, str) or not re.fullmatch(
        r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})', stamp):
        raise ValueError('An explicit RFC3339 offset is required')
    try:
        parsed = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
        if parsed.astimezone(ZoneInfo(zone)).utcoffset() != parsed.utcoffset():
            raise ValueError('Offset does not match birth timezone')
    except (ZoneInfoNotFoundError, TypeError):
        raise ValueError('Valid IANA birth timezone required') from None
    return {'datetime': stamp, 'timezone': zone,
            'latitude': coordinate(value.get('latitude'), 90),
            'longitude': coordinate(value.get('longitude'), 180)}

def birth_values(profile):
    stamp = profile.datetime
    if stamp.tzinfo is None or stamp.utcoffset() is None:
        raise ValueError('Stored birth datetime must be aware')
    # Django stores UTC; restore the same instant in the saved birth zone.
    return birth_input({'datetime': stamp.astimezone(ZoneInfo(profile.timezone)).isoformat(),
                        'timezone': profile.timezone, 'latitude': profile.latitude,
                        'longitude': profile.longitude})

def calendar_values(query):
    day, zone = query.get('date'), query.get('timezone')
    if not isinstance(day, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
        raise ValueError('Explicit date required')
    date.fromisoformat(day)
    if not isinstance(zone, str) or not re.fullmatch(r'[+-]\d{2}:\d{2}', zone):
        raise ValueError('Explicit UTC offset required')
    hours, minutes = map(int, zone[1:].split(':'))
    if hours > 14 or minutes > 59 or (hours == 14 and minutes):
        raise ValueError('Invalid UTC offset')
    return {'date': day, 'timezone': zone, 'latitude': coordinate(query.get('lat'), 90),
            'longitude': coordinate(query.get('lng'), 180)}

def store_chart(profile, envelope):
    if envelope['success'] is not True:
        raise VedikaAPIError('Calculation failed')
    data = envelope['data']
    signs = {p['name']: p['sign'] for p in data['planets']}
    profile.sun_sign, profile.moon_sign = signs.get('Sun', ''), signs.get('Moon', '')
    profile.ascendant = data['ascendant']['sign']
    profile.chart_data = envelope  # Preserve data, billing and public meta.
    profile.save()

class VedikaService:
    _client = None

    @classmethod
    def get_client(cls):
        # One shared client; the views below build a short-lived client per call in _call().
        if cls._client is None:
            cls._client = VedikaClient(api_key=settings.VEDIKA_API_KEY)
        return cls._client

    @staticmethod
    def _call(operation):
        client = VedikaClient(api_key=settings.VEDIKA_API_KEY, timeout=15, max_retries=0)
        envelope = operation(client)
        if not isinstance(envelope, dict) or envelope.get('success') is False:
            raise VedikaAPIError('Calculation failed')
        return envelope

    @classmethod
    def get_birth_chart(cls, profile):
        birth = birth_values(profile)
        return cls._call(lambda client: client.get_birth_chart_v2('birth-chart', birth))

    @classmethod
    def get_kundli_match(cls, first, second):
        # This endpoint takes male birth details first, female birth details second.
        male, female = birth_values(first), birth_values(second)
        return cls._call(lambda client: client.get_compatibility_v2('kundali-matching', male, female))

    @classmethod
    def get_panchang(cls, values):
        return cls._call(lambda client: client.get_panchang(**values))

API Views (DRF)

# charts/views.py
from django.db import transaction
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import APIException, ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from vedika.exceptions import VedikaAPIError
from .models import BirthProfile
from .serializers import BirthProfileSerializer
from .services import VedikaService, store_chart

class BirthProfileViewSet(viewsets.ModelViewSet):
    serializer_class = BirthProfileSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return BirthProfile.objects.filter(user=self.request.user)

    def _update_chart_data(self, profile):
        try:
            store_chart(profile, VedikaService.get_birth_chart(profile))
        except (VedikaAPIError, KeyError, TypeError):
            raise APIException('Calculation failed') from None
        except ValueError:
            raise ValidationError('Invalid birth inputs') from None

    def perform_create(self, serializer):
        with transaction.atomic():
            self._update_chart_data(serializer.save(user=self.request.user))

    def perform_update(self, serializer):
        changed = any(name in serializer.validated_data and
                      serializer.validated_data[name] != getattr(serializer.instance, name)
                      for name in ('datetime', 'latitude', 'longitude', 'timezone'))
        with transaction.atomic():
            profile = serializer.save()
            if changed:
                self._update_chart_data(profile)

    @action(detail=True, methods=['get', 'post'])
    def chart(self, request, pk=None):
        profile = self.get_object()
        if request.method == 'POST':
            self._update_chart_data(profile)
        if profile.chart_data is None:
            return Response({'error': 'POST to generate the chart first'}, status=409)
        return Response(profile.chart_data)  # Reading a stored chart makes no API call.

    @action(detail=True, methods=['post'])
    def match(self, request, pk=None):
        profile = self.get_object()
        identifier = request.data.get('partner_id')
        if isinstance(identifier, bool) or not str(identifier).isdigit() or int(identifier) < 1:
            raise ValidationError('Valid partner_id required')
        partner = get_object_or_404(self.get_queryset(), pk=int(identifier))
        try:
            return Response(VedikaService.get_kundli_match(profile, partner))
        except (VedikaAPIError, KeyError, TypeError):
            raise APIException('Calculation failed') from None

URL Configuration

# charts/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BirthProfileViewSet
from .panchang_views import PanchangView

router = DefaultRouter()
router.register('profiles', BirthProfileViewSet, basename='profile')

urlpatterns = [
    path('api/', include(router.urls)),
    path('api/panchang/', PanchangView.as_view()),
]

# project/urls.py
from django.urls import path, include

urlpatterns = [
    path('', include('charts.urls')),
]

Background Tasks (Celery)

# charts/tasks.py — enqueue only from an authenticated, owner-filtered action
from celery import shared_task
from .models import BirthProfile
from .services import VedikaService, store_chart

@shared_task(autoretry_for=(), max_retries=0)
def generate_chart_async(profile_id, user_id):
    profile = BirthProfile.objects.get(id=profile_id, user_id=user_id)
    store_chart(profile, VedikaService.get_birth_chart(profile))

@shared_task
def send_daily_horoscope():
    # Dead stub retained 2026-10-11/P-161: this block has no delivery call.
    # No schedule is provided; email delivery is a separate authorized workflow.
    from datetime import date
    today = date.today().isoformat()
    profiles = BirthProfile.objects.all()
    for profile in profiles:
        pass

# astrology_project/celery.py — separate file, with your approved broker configured
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'astrology_project.settings')
app = Celery('astrology_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
# astrology_project/__init__.py — separate file
from .celery import app as celery_app

Caching

# charts/panchang_views.py
import hashlib
import json
from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import APIException, ValidationError
from rest_framework.response import Response
from vedika.exceptions import VedikaAPIError
from .services import VedikaService, calendar_values

class PanchangView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        try:
            values = calendar_values(request.query_params)
        except (ValueError, TypeError):
            raise ValidationError('Explicit valid calendar inputs required') from None
        material = json.dumps({'owner': request.user.pk, **values}, sort_keys=True)
        key = 'panchang:' + hashlib.sha256(material.encode()).hexdigest()
        result = cache.get(key)
        if result is None:
            try:
                result = VedikaService.get_panchang(values)
            except VedikaAPIError:
                raise APIException('Calculation failed') from None
            cache.set(key, result, timeout=3600)
        return Response(result)

Admin Interface

# charts/admin.py
from django.contrib import admin
from .models import BirthProfile

@admin.register(BirthProfile)
class BirthProfileAdmin(admin.ModelAdmin):
    list_display = ['name', 'user', 'sun_sign', 'moon_sign', 'created_at']
    list_filter = ['sun_sign', 'moon_sign', 'created_at']
    search_fields = ['name', 'user__username']
    readonly_fields = ['sun_sign', 'moon_sign', 'ascendant', 'chart_data']

Next Steps