python 部署 Django 应用程序后视图不工作

python view not working after deploying django app

我正在尝试使用 apache 和 mod-wsgi 部署一个新的应用程序。该应用程序仅获取 post 请求中提供的日期,并绘制图表和特定时间范围内的 table。 使用 python 内部(开发)Web 服务器似乎可以正确设置日期,但是使用 apache/wsgi 时会失败。问题似乎与视图有关;

# Set initial date
custom_date = [1, 1, 2015]

def GetCustomData(request):
    global custom_date
    form = DateForm()

    if request.method == 'POST':
        custom_date[0] = (str(request.POST['custom_date_day']))
        custom_date[1] = (str(request.POST['custom_date_month']))
        custom_date[2] = (str(request.POST['custom_date_year']))
        date_reformat = datetime.datetime.strptime(str(custom_date[0]+' '+custom_date[1]+' '+custom_date[2]), '%d %m %Y')
        chart_date = date_reformat.strftime('%-d %b %Y')
        return render(request, 'custom_results.html', {'cdate': chart_date})

    else:
        date_reformat = datetime.datetime.strptime(str(custom_date[0]+' '+custom_date[1]+' '+custom_date[2]), '%d %m %Y')
        chart_date = date_reformat.strftime('%-d %b %Y')
        return render(request, 'custom_results.html', {'cdate': chart_date})

当使用 apache 时,最初的 post 请求工作正常,但是当试图导航到 table 的第 2 页时,我得到 "TypeError: cannot concatenate 'str' and 'int' objects" 之后的行 "else" 语句。我假设在 apache 和开发服务器之间更新全局数据变量的方式不同?

您绝不能像这样使用可变全局变量来存储数据。该变量对所有用户都是相同的,这意味着一个用户将能够为所有后续用户更改显示格式。像这样的数据应该存储在会话中。

不过,你的问题的原因要简单得多;默认数据由整数组成,但存储的数据是字符串。通常你应该使用字符串插值而不是连接,但在这里你应该将它存储为一个字符串。

另请注意,if 块的最后三行与 else 块相同;您可以大大简化视图。

def GetCustomData(request):
    if request.method == 'POST':
        request.session['custom_date'] = ' '.join(
            request.POST['custom_date_day'],
            request.POST['custom_date_month'],
            request.POST['custom_date_year']
        )
    custom_date = request.session.setdefault('custom_date', '1 1 2015')
    date_reformat = datetime.datetime.strptime(custom_date, '%d %m %Y')
    chart_date = date_reformat.strftime('%-d %b %Y')
    return render(request, 'custom_results.html', {'cdate': chart_date})