简体   繁体   English

如何将操作结果发送到用户使用django FormView提交表单的模板?

[英]How can I send the result of the operation to the same template where the user submited the form using a django FormView?

Well I want to display the result of an operation which is computed when the user submits the data. 好吧,我想显示用户提交数据时计算出的运算结果。 The problem I'm facing is that I want to use the same template and the FormView class displayed below. 我面临的问题是我想使用相同的模板和下面显示的FormView类。

This is the tempalte. 这是tempalte。 Notice that there is a result if statement at the end of it, where the result of the operation should be displayed: 请注意,在结果末尾有一个if语句,应在其中显示操作结果:

# template
{% block content %}
    {% if form.errors %}
         <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
         </p>
    {% endif %}

    <form action="#" method="post">
        <table>{{ form.as_table }}</table>
        {% csrf_token %}
        <input type="submit" value="Submit" >
    </form>

    {% if res %}
        <p>Result: {{ res|floatformat:3 }}</p>
    {% endif %}

    <a href="{% url logs_page %}">Logs page</a>
{% endblock %}

This is the views.py file. 这是views.py文件。 Notice that I'm trying to send the variable 'result' to the form 请注意,我正在尝试将变量“结果”发送到表单

# views.py
class OperationView(FormView):
   def form_valid(self, form):
      cd = form.clean()
      logged_user = self.request.user
      result = compute_result(cd)
      return super(OperationView, self).form_valid(form, {'result': result})

You would have to go to a class based view, as such: 您将必须转到基于类的视图,例如:

class MyView(View):

    def get(self, request):
        my_form = Formname()
        return render(request, 'template.html', {'my_form': my_form})

    def post(self, request):
        my_form = Formname(request.POST)
        if my_form.is_valid():
            result = do_stuff()
            return render(request, 'template.html', {'my_form': my_form, 'result': result})
        return render(request, 'template.html', {'my_form': my_form})

创建一个新视图,用户在该视图中从模板提交表单,并从该视图呈现包含提交数据的相同模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM