Zach's Mugspideyclick logo

GitHub

GitLab

Linkedin

Instagram

Youtube

SoundCloud

Email

Django Tips

Running an AJAX POST request with CSRF Token

function postRequest(data) {
    let  request  =  new  XMLHttpRequest;
    let  url  =  window.origin  +  '/locationName';
    request.open('POST',  url);
    request.setRequestHeader("Content-Type",  "application/json;charset=UTF-8");
    // This is the important part
    request.setRequestHeader('X-CSRFToken',  Cookies.get('csrftoken'));
    request.send(JSON.stringify(data));
    request.onload  =  function  ()  {
        try  {  output  =  JSON.parse(this.response) }
        catch (err) {  output  =  null  }
        console.log(output);
    };
};

Dealing with timezones

There are a lot of bad solutions for this on the web. The way I see it, the client should send the correct time zone to the server automatically. The server then interprets that timezone in the template that it sends back (uses UTC time during view processing). This is all made possible with the following JavaScript property:

Intl.DateTimeFormat().resolvedOptions().timeZone

Then you can save that to a cookie, load it in views, create a custom filter, register the custom filter, pass the cookie variable back to the webpage as a given variable inside the context, then use that variable as a Django Filter Argument. Yes, it's a lot of steps, but I believe it is the best approach and has only been made available with the introduction and adoption of the above JavaScript property.

Insert the following into your Django project. This would go in your app's directory, something like {projectdir}/app/templatetags/custom_filters.py (also needs __init__.py, see documentation for more info):

import time, datetime, pytz
from django import template

register = template.Library()

@register.filter
def  parsetimestamp(value, arg):
    try:
        clientTz = pytz.timezone(arg)
        utc = pytz.timezone('UTC')
        thisTime = datetime.datetime.fromtimestamp(int(value.split('.')[0]))
        utcTime = utc.localize(thisTime)
        localTime = utcTime.astimezone(clientTz)
        return localTime.strftime("%Y-%m-%d %I:%M %p")
    except:
        return  "parsetimestamp failed (expects string of float epoch)"

Iterating in Django Templates

You can't access dictionary items with brackets ({{ dict['key'] }}). Instead, you have to use period: {{ dict.key }}

Every For Loop has a counter associated with it: {{ forloop.counter }}. I am not sure at this time how that works with nested loops.