Django:上下文处理器和基于类的视图

时间:2018-08-08 12:12:25

标签: python django

我正试图在某些页面上包含一个表单,以处理生成/通过电子邮件发送报告。

# context_processors.py
def sales_report_form(request):
    if request.method == 'POST':
        form = SalesPdfForm(request.POST or None)
        if request.user.email:
            if form.is_valid():
                form.generate_pdf()
                messages.success(request, 'Report will be emailed to {} shortly.'.format(request.user.email))
        else:
            messages.error(request, 'No email address set for {}'.format(request.user.username))
        return redirect(request.path)
    else:
        return {'sales_report_form': SalesPdfForm()}

该表单显示在页面上,但发布时遇到问题

Method Not Allowed (POST): /path/
"POST /path/ HTTP/1.1" 405 0

为了允许发布,我将逻辑移至mixin并将其添加到每个视图。这是在基于类的视图中处理上下文处理器表单发布的正确方法吗?

class SalesReportMixin(object):
    """
    CBV mixin to handle the generation of sales reports.
    """
    def post(self, request, *args, **kwargs):
        if 'sales_report' in request.POST:
            form = SalesPdfForm(request.POST or None)
            if request.user.email:
                if form.is_valid():
                    form.generate_pdf()
                    messages.success(request, 'Report will be emailed to {} shortly.'.format(request.user.email))
            else:
                messages.error(request, 'No email address set for {}'.format(request.user.username))
            return redirect(request.path)
        return super(SalesReportMixin, self).post(request, *args, **kwargs)

0 个答案:

没有答案