简体   繁体   English

在Django中,如何添加两个字段的内容并在第三个字段中显示结果?

[英]In Django, how do I add the contents of two fields and display the results in a third field?

I'm trying to learn Django and am finding it frustratingly difficult to do fairly basic things.我正在尝试学习 Django,但发现做相当基本的事情非常困难。 I have the following form classes:我有以下表单类:

from django import forms

class InputForm(forms.Form):
  field1 = forms.FloatField(label="First field: ")
  field2 = forms.FloatField(label="Second field: ")

class OutputForm(forms.Form):
  outfield = forms.FloatField(label="Result: ")

And the following template:以及以下模板:

<form>
    {{ input_form.as_ul }}
    <input type="submit" class="btn" value="Submit" name="submit_button">
</form>

<form>
    {{ output_form.as_ul }}
</form>

And finally, the following view:最后,以下观点:

from django.shortcuts import render
from .forms import InputForm, OutputForm

def index(request):

    if request.GET.get('submit_button'):
        # ?????

    else:
        input_form = InputForm()
        output_form = OutputForm()
        return render(request, 'index.html', {'input_form': input_form, 
                                            'output_form': output_form})

All I want to happen is that when I hit the submit button, the values in first field and second field get added and displayed in the result field.我想要发生的是,当我点击提交按钮时,第一个字段和第二个字段中的值被添加并显示在结果字段中。 I know from debug outputs that the ?????我从调试输出中知道 ????? commented block is run when I press the button, but I have so far not been able to figure out what to do to actually access or alter the data in my fields.当我按下按钮时,注释块会运行,但到目前为止我还没有弄清楚如何实际访问或更改我的字段中的数据。 I don't care about keeping a record of these transactions so it feels like storing these in a database is tremendous overkill.我不在乎保留这些交易的记录,所以感觉将这些存储在数据库中是非常矫枉过正的。 What is the correct way to approach this?解决这个问题的正确方法是什么?

There's a few things at work here, lets go through them one by one.这里有一些事情在起作用,让我们一一进行。

1. Calculating the output value 1. 计算输出值

Use the request data to build the form, validate it, and then calculate the sum:使用请求数据构建表单,验证它,然后计算总和:

if request.GET.get('submit_button'):
    input_form = InputForm(request.GET)
    if input_form.is_valid():
       data = input_form.cleaned_data
       result = data["field1"] + data["field2"]

2. Read-only output 2. 只读输出

It's not clear why you're using a submittable form field for data that is to be calculated by your app, as opposed to playing the result into a regular html 'label' in the template.不清楚为什么您要为应用程序计算的数据使用可提交的表单字段,而不是将结果播放到模板中的常规 html“标签”中。 If you really want/need to set the result in a form field, I'd at least make it read-only.如果您真的想要/需要在表单字段中设置结果,我至少会将其设为只读。 See In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?请参阅在 Django 表单中,如何将字段设为只读(或禁用)以使其无法编辑? for an example of how to do that.有关如何执行此操作的示例。

3. Set the output data in the form 3.在表格中设置输出数据

Set the output form/field's initial data to the result you have calculated.将输出表单/字段的initial数据设置为您计算的结果。 following on form the code at (1):在 (1) 处形成代码:

       result = data["field1"] + data["field2"]
       output_form = OutputForm(initial={"outfield": result})

then render the view as you're already doing:然后像你已经在做的那样渲染视图:

       return render(
           request,
           'index.html',
           {'input_form': input_form, 'output_form': output_form},
       )

You don't need a form to display the result.您不需要表单来显示结果。 When the form is valid, you can get the values from the form's cleaned_data and calculate result .当表单有效时,您可以从表单的cleaned_data获取值并计算result

def index(request):
    result = None  # Set to None by default

    if request.GET.get('submit_button'):  # The submit button was pressed
        input_form = InputForm(request.GET)  # Bind the form to the GET data
        if input_form.is_valid():
            result = input_form.cleaned_data['field1'] + input_form.cleaned_data['field2']  # Calculate the result
    else:
        input_form = InputForm()  # Submit button was not pressed - create an unbound (blank) form
    return render(request, 'index.html', {'input_form': input_form, result:result})

Then in your template, include {{ result }} instead of the output form.然后在您的模板中,包含{{ result }}而不是输出表单。

Setting the initial poperty on a field prefills it:在字段上设置初始 poperty 会对其进行预填充:

output_form.fields['outfield'].initial = input_form.data.get ('field1') + input_form.data.get ('field1')

You need to pass request.POST or request.GET into OutputForm when you instantiate it.实例化时,您需要将 request.POST 或 request.GET 传递到 OutputForm 中。 You should also be calling is_valid() on the from and using cleaned_data instead of data after you check if it is valid.您还应该在 from 上调用 is_valid() 并在检查它是否有效后使用cleaned_data 而不是 data 。

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

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