生产环境登录触发Django 500内部服务器错误求助
Hey there! Let's break down why you're hitting that 500 error only when entering valid login credentials on your Django 2.2 site deployed on Apache + Dataplicity—especially since runserver works fine and wrong credentials behave as expected. Here are the most likely fixes to try:
1. First, Capture the Exact Django Error (Apache Logs Won’t Show This)
Apache’s error log isn’t picking up the issue, so we need to enable Django’s own logging to get the root cause. Add this configuration to your settings.py:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/pi/pi_site/django_error.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, }
Save the file, restart Apache with sudo systemctl restart apache2, then try logging in again. Open /home/pi/pi_site/django_error.log—it’ll tell you exactly what’s breaking (e.g., permission issues, missing dependencies, etc.).
2. Fix File Permissions (Most Likely Culprit)
When you run manage.py runserver, you’re using your pi user which has full access to your project files. But Apache runs as the www-data user, which might not have write permissions for critical files like your SQLite database.
Valid login attempts try to write a session to the database, which fails if www-data can’t modify db.sqlite3. Wrong credentials don’t trigger this write operation, hence no error.
Fix the permissions with these commands:
# Give www-data ownership of your project directory sudo chown -R www-data:www-data /home/pi/pi_site/ # Set appropriate read/write/execute permissions sudo chmod -R 755 /home/pi/pi_site/
Restart Apache and test the login again.
3. Verify Your WSGI Virtual Environment Setup
Double-check that Apache is using the correct virtual environment. Sometimes the WSGIPythonHome or WSGIPythonPath in apache2.conf can be misconfigured, leading to missing dependencies even if runserver works perfectly.
Add these lines to your wsgi.py to explicitly point to your virtual environment’s packages (replace python3.x with your actual Python version, e.g., python3.7):
import sys import os # Add project root to path sys.path.append('/home/pi/pi_site') # Add virtual environment site-packages to path sys.path.append('/home/pi/pi_site/myvenv/lib/python3.x/site-packages')
Restart Apache after making this change.
4. Quick Sanity Checks
- Confirm your
STATIC_ROOTdirectory (/home/pi/pi_site/static/) has read permissions forwww-data(though this is less likely to cause login-specific errors). - Ensure
ALLOWED_HOSTScovers your full Dataplicity subdomain (your current".dataplicity.io"should work for all subdomains, but double-check if your actual URL matches).
内容的提问来源于stack exchange,提问作者Elephant

