Home > Blockchain >  JSON local file retrieval with internationalization in django
JSON local file retrieval with internationalization in django

Time:05-31

I am making a website in django and have included internationalization. The internationalization works fine on other pages, except for when I am trying to retrieve a json file.

The search takes in a word, then finds the corresponding JSON file in the javascript file (below). The search was working without issue until I added internationalization. Now I can see that when jquery goes to get the file, it includes the i18n abbreviation on the front, resulting in a 500 error. I have tried parsing the file location but the abbreviations are always added in getJSON. How do I fix this issue?

The error specifically that shows in the console is:

GET http://localhost:8000/en/static/assets/chowords/amo.json 500 (Internal Server Error)

It makes sense that that is an error since the json file is actually at http://localhost:8000/static/assets/chowords/amo.json I tried storing the files in a directory "en" with static nested inside, but that did not resolve the issue.

Code for reference:

  1. Javascript file
new URLSearchParams(window.location.search).forEach((value,name)=>{

    console.log(name)
    console.log(value)
    var fileword = value;

    var url = "./static/assets/chowords/"   fileword   ".json";

    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', url, false);
    xhr.send();
    console.log(xhr)

    document.getElementById("wordsearched").innerHTML =`<h1>${fileword} </h1>`

    if (xhr.status == "404") {
        //console.log("File doesn't exists");
        let div = document.createElement('p')
        div.innerHTML =`<h3>No results found</h3>`
        document.getElementById("word").appendChild(div)

    } else  {
        console.log("here");
        $.getJSON("static/assets/chowords/"   fileword   ".json", function(data){

                var senses = data['sense'];
                console.log(senses.length)
                var audios = data['audio']
                var variant = data['variant']

                for (var i = 0; i <senses.length; i  ){
                    let wording = senses[i];
                    wordtemplate(wording, audios, variant)
                }
            });
    }
    })
  1. settings.py showing codes for internationalization
"""
Django settings for mbci_website project.

Generated by 'django-admin startproject' using Django 3.0.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _
from django.conf import global_settings
import json

gettext_noop = lambda s: s

LANGUAGES = (
       ('ch', gettext_noop('Chahta')),
        ('en', _('English')),
)

EXTRA_LANG_INFO = {
    'ch': {
        'bidi': True, # right-to-left
        'code': 'ch',
        'name': 'Choctaw',
        'name_local': u'Chahta', #unicode codepoints here
    },
}

# Add custom languages not provided by Django
import django.conf.locale
LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO)
django.conf.locale.LANG_INFO = LANG_INFO

# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI   ["ch"]

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pt%& )^#hgpn@yq1srv xh4%_zo7od^ek5@z2t2tbb@2dt%9##'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mbci_website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mbci_website.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

LANGUAGE_CODE = 'ch'


LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

Many thanks for any help on this!

CodePudding user response:

This is a relative path

 $.getJSON("static/assets/chowords/"...

Change it to

$.getJSON("/static/assets/chowords/"...

so it becomes absolute.

Also, to view the error message, you can go in the "Network" tab in developer tools, select the request which had an error then go to the preview tab.

  • Related