Django Middleware打破表单提交?

时间:2017-11-05 14:44:05

标签: python django forms django-middleware

当我添加中间件时,TemplateResponse页面上的表单停止工作:提交会导致加载几分钟,然后导致负载均衡器错误。

form中未定义中间件时,process_imgbot方法和settings.py查看完全按预期工作。

代码:

在settings.py中:

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',
    'polls.views.ExampleMiddleware'
]

MIDDLEWARE_CLASSES = [
    'polls.views.ExampleMiddleware'
]

views.py中的中间件定义:

class ExampleMiddleware(MiddlewareMixin):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_template_response(self, request, response):
        if 'right' in request.POST:
            response.context_data['response'] = 'Sweet, thanks!'
        elif 'wrong' in request.POST:
            response.context_data['response'] = 'Awww, sorry'
        return response

views.py中的相关观点:

def bot(request):
    img_form = ImageUploadForm()
    context = {'img_form':img_form}
    if request.method=='POST':
        img_form = ImageUploadForm(request.POST, request.FILES)
        if img_form.is_valid():
            myfile = request.FILES['image']
            context = process_img(myfile)
            return TemplateResponse(request, 'polls/bot.html',context)
    return TemplateResponse(request, 'polls/bot.html',context)

详细信息:Python 3.5,Django 1.11,在任何地方托管Python。

什么打破了表单提交以及如何解决?

编辑:服务器日志说

  

2017-11-05 16:56:26 Sun Nov 5 16:56:25 2017 - * HARAKIRI ON WORKER   2(pid:15659,尝试:1)*

     

2017-11-05 16:56:26 Sun 11月5日16:56:25 - HARAKIRI !!!工人2   状态!!!

     

2017-11-05 16:56:26 Sun Nov 5 16:56:25 2017 - HARAKIRI [core 0]   10.0.0.222 - POST /自1509900084以来

     

2017-11-05 16:56:26 Sun 11月5日16:56:25 - HARAKIRI !!!结束   工人2状态!!!

     

2017-11-05 16:56:26 DAMN!工人2(pid:15659)死亡,被杀害   信号9 :(尝试重生......

     

2017-11-05 16:56:26重生的uWSGI工人2(新pid:20420)

     

2017-11-05 16:56:26为uWSGI worker 2生成2个卸载线程

1 个答案:

答案 0 :(得分:0)

根据你的settings.py,你忘了在逗号后面加上逗号;' django.contrib.messages.middleware.MessageMiddleware'"。

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',
'polls.views.ExampleMiddleware'
]