Django项目中聊天机器人训练数据文件的存储位置及正确加载方法
Hey, I’ve run into exactly this issue when deploying a custom chatbot on Django before! That FileNotFoundError is tricky because it feels like the files are right there, but Django’s working directory when the server starts throws you off. Let’s break down the solutions:
1. Where should you store these training data files?
- The best place is right in the same app directory as your
views.py(somysite/polls/in your case). You don’t need to put them in the static files directory—static folders are for frontend assets like CSS, JS, and images. Your model and training data are backend dependencies, so keeping them with your app code makes way more sense for organization and access.
2. How to correctly load the files in views.py?
The problem is that using relative paths like 'intents.json' doesn’t work—when Django starts the server, its working directory is your project root (mysite/), not your app directory (mysite/polls/). So it’s looking for the file in the wrong place!
Fix this by using absolute paths with Python’s os module and the __file__ variable (which points to your current views.py file). Here’s how to modify your code:
from django.shortcuts import render from django.http import HttpResponse import os # Add this import import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np from keras.models import load_model import json import random # Get the absolute path of the directory where views.py lives BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def index(request): # Use BASE_DIR to build the full path to each file intents = json.loads(open(os.path.join(BASE_DIR, 'intents.json')).read()) model = load_model(os.path.join(BASE_DIR, 'chatbot_model.h5')) words = pickle.load(open(os.path.join(BASE_DIR, 'words.pkl'), 'rb')) classes = pickle.load(open(os.path.join(BASE_DIR, 'classes.pkl'), 'rb')) # Rest of your code (clean_up_sentence, bow, etc.) stays the same... return render(request, "index.html")
This works because os.path.abspath(__file__) gives you the full path to views.py, os.path.dirname grabs the directory it’s in, and os.path.join safely combines that directory path with your filenames—no matter where Django’s working directory is, it’ll find the files.
3. Should you put these files in the static directory?
Nope, absolutely not! The static directory is meant for assets that the frontend needs to access directly. Your training data and model are backend-only files that your Python code loads at runtime. Keeping them in your app directory follows Django’s project structure best practices and avoids unnecessary static configuration headaches.
内容的提问来源于stack exchange,提问作者muellerjustin

