我在同一台服务器上有两个Django网站,它们使用带有mod_wsgi的Apache(windows 10(。我的第一个Django网站运行良好,它简单得多,但我的第二个网站则不然。一旦我连接到它,它的加载速度非常慢,但是,我无法再次连接到它(它只是保持在没有错误的连接阶段(。我遇到这个问题已经有很长一段时间了,下面是我的其他帖子。
- 只有第一个被加载的Django站点工作
- 使用mod_wsgi在apache上进行多次请求后的Django无限加载
- Django网站未加载
编辑: 我可以确认错误肯定在Mainfront(前端应用程序(视图.py中,但我不知道为什么这是我的index.html,如果我删除{%%}及其内容,问题就会消失,有什么想法吗?
<div class="col-md-12">
{% for instance in object_list %}
<div class="card">
<div class="card-body">
<span class="author card-header float-right">Posted by {{ instance.user }}, {{ instance.created_at }}</span>
<h2 style="color: black;" class="card-title font-weight-bold text-uppercase">{{ instance.title }}</h2>
{{ instance.body|safe }}
</div>
</div>
{% endfor %}
</div>
调试:
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
(0.000) SELECT "mainfront_article"."id", "mainfront_article"."title", "mainfront_article"."body", "mainfront_article"."created_at", "mainfront_article"."user_id" FROM "mainfront_article" ORDER BY "mainfront_article"."created_at" DESC; args=(); alias=default
直到最近,我才将问题定位到这个特定的Django项目中,我将在下面提供我的大部分代码。希望有人能告诉我我做错了什么。如果这还不够,请联系我,谢谢。
基本URL.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/", include("accounts.urls")),
path('', include('mainfront.urls')),
path('about/', include('mainfront.urls')),
path('contact/', include('mainfront.urls')),
path('home/', include('mainfront.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
基本WSGI
import os
from django.core.wsgi import get_wsgi_application
import sys
sys.path.append('C:/xampp/htdocs/neostorm')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'neostorm.settings')
application = get_wsgi_application()
Mainfront(前端应用程序(视图.py
from django.shortcuts import render
import threading
from mcstatus import JavaServer
from .models import Article
#Query the minecraft server every 5 seconds
def queryserver():
threading.Timer(5.0, queryserver).start()
server = JavaServer.lookup("neostorm.us.to:25565")
try:
global status
server.status().latency
global playersonline
playersonline = server.status().players.online
except:
status='Offline'
playersonline='n/a'
else:
status='Online'
queryserver()
# Create your views here.
def index(request):
#Sort Article class by date of created date and updated date
obj = Article.objects.order_by('-created_at')[:10]
article_context = {
"object_list":obj
}
return render(request, 'mainfront/index.html', {'playeronline' : playersonline, 'status' : status} | article_context)
def about(request):
return render(request, 'mainfront/About.html')
def contact(request):
return render(request, 'mainfront/Contact.html')
主前端型号.py
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth.models import User
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=50)
body = RichTextUploadingField(blank=True, null=True)
#Order the articles model by the date of update
created_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False)
设置.py
"""
Django settings for neostorm project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path, os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'fdsy874ybfrdeouit6487t64986483699676966nope'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['neostorm.us.to', '127.0.0.1']
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'C:/xampp/htdocs/neostorm/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sessions',
'ckeditor',
'ckeditor_uploader',
'mainfront', #front page (home, about and contact)
]
CKEDITOR_UPLOAD_PATH = 'articles/'
CKEDITORBackGround = '#7D001D'
CKEDITOR_CONFIGS = {
'default': {
'skin': 'moono-lisa',
'toolbar_Basic': [
['Source', '-', 'Bold', 'Italic']
],
'toolbar_YourCustomToolbarConfig': [
{'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
{'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
{'name': 'forms',
'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
'HiddenField']},
'/',
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
'Language']},
{'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
{'name': 'insert',
'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['Maximize', 'ShowBlocks']},
'/', # put this to force next toolbar on new line
{'name': 'yourcustomtools', 'items': [
# put the name of your editor.ui.addButton here
'Preview',
'Maximize',
]},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
# 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],
# 'height': 291,
# 'width': '100%',
# 'filebrowserWindowHeight': 725,
# 'filebrowserWindowWidth': 940,
# 'toolbarCanCollapse': True,
# 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
'tabSpaces': 4,
'extraPlugins': ','.join([
'uploadimage', # the upload image feature
# your extra plugins here
'div',
'autolink',
'autoembed',
'embedsemantic',
'autogrow',
'widget',
'lineutils',
'clipboard',
'dialog',
'dialogui',
'elementspath'
]),
}
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'neostorm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'neostorm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Australia/Melbourne'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "images/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
我的解决方案是从默认数据库切换到MySQL。我不完全确定为什么默认数据库会损坏。
如果你想切换到MySQL,这就是你可以做的。
在你的设置中。找到数据库并制作它。
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.mysql', # <-- UPDATED line
'NAME' : 'DATABASE_NAME', # <-- UPDATED line
'USER' : 'USER', # <-- UPDATED line
'PASSWORD': 'PASSWORD', # <-- UPDATED line
'HOST' : 'localhost', # <-- UPDATED line
'PORT' : '3306',
}
}