JSON 在 Django 中进行国际化的本地文件检索

JSON local file retrieval with internationalization in django

我正在用 django 制作一个网站,并且包含了国际化。国际化在其他页面上工作正常,除了当我试图检索 json 文件时。

搜索取一个词,然后在javascript文件(下)中找到对应的JSON文件。在我添加国际化之前,搜索一直没有问题。现在可以看到jquery去获取文件的时候,前面包含了i18n缩写,导致500错误。我尝试解析文件位置,但缩写总是添加到 getJSON 中。我该如何解决这个问题?

控制台中具体显示的错误是:

获取 http://localhost:8000/en/static/assets/chowords/amo.json 500(内部服务器错误)

这是一个错误是有道理的,因为 json 文件实际上位于 http://localhost:8000/static/assets/chowords/amo.json 我尝试将文件存储在目录“en”中,其中嵌套了 static,但这并没有解决问题。

参考代码:

  1. Javascript 文件
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 显示国际化代码
"""
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'),)

非常感谢您对此提供的任何帮助!

这是相对路径

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

改为

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

所以它变得绝对。

此外,要查看错误消息,您可以进入开发人员工具中的“网络”选项卡,select 出错的请求然后转到预览选项卡。