You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django部署TimeWeb后HttpResponseRedirect等重定向异常问题

Django部署至TimeWeb后的无限加载问题

我开发了一个支持文件上传下载及发布功能的Web应用,使用Django 5.0.1和Python 3.10.2。本地localhost运行正常,但部署至TimeWeb主机后,出现以下问题:

  • 无法登录admin面板及账号系统,页面无限加载;
  • 新增发布后,数据能成功创建,但重定向至该发布详情页时同样无限加载,跳转至旧发布详情页则正常,怀疑是新数据库数据的重定向问题。

已尝试的解决措施:

  • 将HttpResponseRedirect替换为redirect,问题未解决;
  • 重装Django和Python,检查依赖库,无效果;
  • 服务器错误日志为空。

views.py中的detail和add函数

def detail(request, publication_id):
    auth = request.user.is_authenticated

    grade5 = Publication.objects.get(pk=publication_id).grade5
    grade6 = Publication.objects.get(pk=publication_id).grade6
    grade7 = Publication.objects.get(pk=publication_id).grade7
    grade8 = Publication.objects.get(pk=publication_id).grade8
    grade9 = Publication.objects.get(pk=publication_id).grade9
    grade10 = Publication.objects.get(pk=publication_id).grade10
    grade11 = Publication.objects.get(pk=publication_id).grade11

    lettera = Publication.objects.get(pk=publication_id).lettera
    letterb = Publication.objects.get(pk=publication_id).letterb
    letterv = Publication.objects.get(pk=publication_id).letterv
    letterg = Publication.objects.get(pk=publication_id).letterg
    letterd = Publication.objects.get(pk=publication_id).letterd

    letter = (lettera*"А") + (letterb*"Б") + (letterv*"В") + (letterg*"Г") + (letterd*"Д")
    grade = (grade5 * "5") + (grade6 * "6") + (grade7 * "7") + (grade8 * "8") + (grade9 * "9") + (grade10 * "10") + (grade11 * "11")+ " "
    if (len(letter)>1):letter = "вся параллель"
    if (len(grade)>2):grade = "все параллели, "

    return render(request, "schoolbase/detail.html",
        {
            "auth": auth,
            "Publication":Publication.objects.get(pk=publication_id),
            "grade":grade+letter,
            "category": Publication.objects.get(pk=publication_id).category_any * "общая" + Publication.objects.get(pk=publication_id).category_olympiad * "олимпиадная" + Publication.objects.get(pk=publication_id).category_educational * "учебная" + Publication.objects.get(pk=publication_id).category_schedule * "расписание" + Publication.objects.get(pk=publication_id).category_menu * "меню столовой",
        }
        )


def add(request):
    try:
        newp_name = request.POST["Publication_name"]
        newp_text = request.POST["Publication_text"]
        grades = int(request.POST["grade"])
        letters = int(request.POST["class"])
        categories = request.POST["category"]
        
        Pre_grade5 = False
        Pre_grade6 = False
        Pre_grade7 = False
        Pre_grade8 = False
        Pre_grade9 = False
        Pre_grade10 = False
        Pre_grade11 = False

        if (grades == 5): Pre_grade5 = True
        elif (grades == 6): Pre_grade6 = True
        elif (grades == 7): Pre_grade7 = True
        elif (grades == 8): Pre_grade8 = True
        elif (grades == 9): Pre_grade9 = True
        elif (grades == 10): Pre_grade10 = True
        elif (grades == 11): Pre_grade11 = True
        else:
            Pre_grade5 = True
            Pre_grade6 = True
            Pre_grade7 = True
            Pre_grade8 = True
            Pre_grade9 = True
            Pre_grade10 = True
            Pre_grade11 = True
        
        Pre_lettera = False
        Pre_letterb = False
        Pre_letterv = False
        Pre_letterg = False
        Pre_letterd = False

        if (letters == 5):
            Pre_lettera = True
            Pre_letterb = True
            Pre_letterv = True
            Pre_letterg = True
            Pre_letterd = True
        elif (letters == 0): Pre_lettera = True
        elif (letters == 1): Pre_letterb = True
        elif (letters == 2): Pre_letterv = True
        elif (letters == 3): Pre_letterg = True
        elif (letters == 4): Pre_letterd = True

        anyy = False
        olympiad = False
        educational = False
        schedule = False
        menu = False

        if (categories == "any"): anyy = True
        elif (categories == "olympiad"): olympiad = True
        elif (categories == "educational"): educational = True
        elif (categories == "schedule"): schedule = True
        elif (categories == "menu"): menu = True
    except (KeyError):
        return render(request, "schoolbase/add.html")
            
    else:
        publ = Publication(Publication_name = newp_name, Publication_text = newp_text, pub_date=timezone.now(),
            grade5 = Pre_grade5,
            grade6 = Pre_grade6,
            grade7 = Pre_grade7,
            grade8 = Pre_grade8,
            grade9 = Pre_grade9,
            grade10 = Pre_grade10,
            grade11 = Pre_grade11,
            lettera = Pre_lettera,
            letterb = Pre_letterb,
            letterv = Pre_letterv,
            letterg = Pre_letterg,
            letterd = Pre_letterd,
            category_any = anyy,
            category_olympiad = olympiad,
            category_educational = educational,
            category_schedule = schedule,
            category_menu = menu,
            #Publication_author = request.user.first_name,
            )
        publ.save()
        return HttpResponseRedirect(reverse("detail", args=(publ.id,)))

settings.py配置

from pathlib import Path
import 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/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%esmk3vc)-6xe8(j#=gr7&cf6jurgo#a85xq*e2xqr#+v-d)5r'

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

ALLOWED_HOSTS = ['*']


# Application definition

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

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 = 'mysite.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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.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/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Moscow'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


MEDIA_DIR = os.path.join(BASE_DIR,'media')
#Media
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = '/schoolbase/index'
LOGOUT_REDIRECT_URL = '/schoolbase/index'

urls.py配置

from django.urls import path, include, re_path
from django.contrib.auth.views import LogoutView
from .views import logout_view

from . import views

from django.views.generic.base import RedirectView

favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)

urlpatterns = [
    path("", views.index, name="index"),
    path("add/", views.add, name="add"),
    path("success/", views.success, name="success"),
    path("<int:publication_id>/", views.detail, name="detail"),
    path('download/<int:file_id>/', views.download_file, name='download_file'),
    path('logout/', logout_view, name='logout'),
    re_path(r'^favicon\.ico$', favicon_view),
]

wsgi.py配置

import os
import sys

try:
  sys.path.remove('/home/c/cs40246/venv/lib/python3/dist-packages')
except:
  pass

sys.path.append('/home/c/cs40246/public_html/mysite/')
sys.path.append('/home/c/cs40246/venv/lib/python3.10/Lib/site-packages/')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

内容的提问来源于stack exchange,提问作者SIR_WIZIX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:09:51