子类post方法返回不同的模板和上下文

2024-09-27 00:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想能够采取相同的形式输入,并使用它来做计算(使用不同的网址)为不同的产品,并发送产品结果到一个产品模板

我试着用get和post方法创建一个基类,子类(不同的产品url)将从中继承,尤其是post方法,以保持干燥

from .models import InputForm

class InputView(TemplateView):
    template_name = 'input.html'

    def get(self, request, *args, **kwargs):
        form = InputForm()
        return render(request, self.template_name, {'form': form})


    def post(self, request, *args, **kwargs):
        form = InputForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            a =cleaned_data['mbr_l']
            b =cleaned_data['es_l']
            c =cleaned_data['wic_l']
            d =cleaned_data['br2_l']

            length = a + b + c + d

            qty = 0.8*length

            return render(request, 'result.html',  {'qty': qty})


        else:
            return render(request, self.template_name, {'form': form})

class B(InputView):
    def post(self, request, *args, **kwargs):
        qty2 = super().post(self, request, *args, **kwargs)

        return super().render(request, 'result2.html',  {'qty2': qty2})
url conf:
urlpatterns = [
    path('product1', InputView.as_view()),
    path('product2',B.as_view()),
 ]

templates:

template1
<td>{{qty1}}</td>

template2
<td>{{qty2}}</td>




我希望url conf中的url product2进行计算并将context(qty2)发送到results2.html,但它总是用qty呈现results.html,这是正确的,因为B继承InputView和所有方法。我并不真的希望render方法的super调用是有效的,但这是我多次尝试的最后一次


Tags: 方法selfformurldata产品requesthtml

热门问题