← Integrations

Backend · Python

Storing birth data in Django so the API gets the right time

The HTTP call is the easy part of a Django integration. The part that silently corrupts results is the model: store a birth as one aware DateTimeField and Django hands it back in UTC. This page shows the three-field model, a stdlib client, and what the UTC mistake did to a real chart.

Updated

How this page was checked: charts/astronode.py was executed as written on Python 3.9 against the in-memory API, with django.conf.settings and django.core.cache replaced by stand-ins (Django is not installed on the build machine). The model and view are not executed.

The model: three fields, not one

charts/models.py:

python
from django.db import models


class BirthProfile(models.Model):
    user = models.OneToOneField("auth.User", on_delete=models.CASCADE)
    birth_date = models.DateField()
    birth_time = models.TimeField()                     # wall-clock time at the birthplace
    birth_tz_offset_minutes = models.SmallIntegerField()  # offset in force then, e.g. 330
    birth_lat = models.DecimalField(max_digits=8, decimal_places=5)
    birth_lng = models.DecimalField(max_digits=8, decimal_places=5)
    birth_place_label = models.CharField(max_length=200)  # display only, never sent

This is exactly what the API takes: a civil date, a local time, and the offset that was in force at that place and date. Keep them separate and nothing in Django's time-zone machinery can rewrite them.

A client with no new dependency

Settings hold the key (ASTRONODE_API_KEY = os.environ["ASTRONODE_API_KEY"]) and ASTRONODE_BASE_URL. The client uses urllib, so it adds nothing to requirements.txt; swap in requests if you already use it.

charts/astronode.py:

python
import hashlib
import json
import urllib.error
import urllib.request

from django.conf import settings
from django.core.cache import cache


class AstroNodeError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code = status, code


def _post(path, body):
    req = urllib.request.Request(
        settings.ASTRONODE_BASE_URL + path,
        data=json.dumps(body).encode(),
        headers={
            "Authorization": f"Bearer {settings.ASTRONODE_API_KEY}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as res:
            return json.load(res)["data"]
    except urllib.error.HTTPError as err:
        error = json.load(err)["error"]
        raise AstroNodeError(err.code, error["code"], error["message"]) from None


def birth_payload(profile):
    """Build the request from the three stored fields - never from a DateTimeField."""
    return {
        "date": profile.birth_date.isoformat(),               # DateField
        "time": profile.birth_time.strftime("%H:%M:%S"),      # TimeField
        "tz_offset_minutes": profile.birth_tz_offset_minutes,  # SmallIntegerField
        "lat": float(profile.birth_lat),
        "lng": float(profile.birth_lng),
    }


def present_yogas(profile):
    body = birth_payload(profile)
    key = "yogas:" + hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
    data = cache.get(key)
    if data is None:
        data = _post("/v1/yogas", body)
        cache.set(key, data, timeout=None)  # deterministic: same input, same output
    return [y for y in data["yogas"] if y["present"]]

float(...) matters: DecimalField values are Decimal, which json.dumps refuses to serialise. timeout=None caches forever, which is safe because the same birth always produces the same yogas for a given engine version.

For the sample profile (24 April 1973, 17:25, Mumbai) present_yogas returned 10 of the 55 yogas the engine checks: Vesi, Vasi, Ubhayachari, Sunafa, Sankha, Raja Yoga, Kaala Sarpa, Vimala, Paasha and Shakata, each with a reason such as "Planet(s) in 2nd from Sun: Saturn.". A view can pass that list straight to a template; the full catalog is in the yoga reference.

The mistake that bites first: USE_TZ and a single DateTimeField

With USE_TZ = True (the default), Django stores aware datetimes in UTC and returns them in UTC. Save the birth as 17:25+05:30, read it back, call strftime("%H:%M:%S"), and you send 11:55:00 - the UTC time - alongside tz_offset_minutes: 330. The API then treats 11:55 as Mumbai time, nearly five and a half hours early.

Same birth, real responses
SentAscendant (/v1/charts/birth)Yogas present
time: "17:25:00", offset 330 (correct)Virgo 19.76°10
time: "11:55:00", offset 330 (UTC read back)Cancer 3.30°16

Nothing errors - you just get someone else's chart. If you already have a DateTimeField, convert it back with value.astimezone(timezone(timedelta(minutes=offset))) before formatting, then migrate to separate fields. The ascendant off by a sign page lists the other ways time gets shifted.

Questions

Which AstroNode endpoints does the Django example call?
2 endpoints: Yoga Detection (POST /v1/yogas); Birth Chart (Kundli) (POST /v1/charts/birth).
Was the Django code on this page actually run?
charts/astronode.py was executed as written on Python 3.9 against the in-memory API, with django.conf.settings and django.core.cache replaced by stand-ins (Django is not installed on the build machine). The model and view are not executed.