django 我如何更改表单字段填充 * 后 * 成功的基于类的视图的POST请求

3yhwsihp  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(127)

我想更改表单的初始字段填充。这是一个陷阱:我想为POST请求而不是GET请求更改它。
假设我的应用程序提供了一个基于体重输入的计算。如果用户输入体重,则使用该体重进行体重计算,否则使用默认值50。因此允许让字段为空。但是在计算运行之后,我想显示用于计算的值为50。这就是为什么我想在表单最初提交为空值后用50填充字段的原因。

# forms.py
class CalculatorForm(forms.Form):
    body_weight = forms.FloatField(required=False)

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['body_weight'] is None:
            cleaned_data['body_weight'] = 50.0
        # ideally I want to put the logic here
        # self.data[bpka] = 50.0 --> AttributeError: This QueryDict instance is immutable
        # self.fields['body_weight'] = 50.0 --> does not work
        # self.initial.update({'body_weight': 50.0}) --> does not work
        return cleaned_data

我觉得问题是我无法从clean()方法访问绑定字段。
如果在表单中不可能,我想逻辑必须转到视图。在这里随意修改:

class CalculatorView(FormView):
    template_name = 'myapp/mycalculator.html'
    form_class = CalculatorForm

    def get_context_data(self, res=None, **kwargs):
        context = super().get_context_data(**kwargs)
        if res is not None:
            context['result'] = res
        return context

    def form_valid(self, form, *args, **kwargs):
        # form['body_weight'] = 50.0 --> does not work
        res = form.cleaned_data['body_weight'] / 2
        return render(
            self.request,
            self.template_name,
            context=self.get_context_data(res=res, **kwargs)
        )
kd3sttzy

kd3sttzy1#

您可以重写.form_valid,因为当有效的表单数据已被POST时会调用该方法。通过这种方式,创建一个具有所需initial值的CalculatorForm的新示例,而不是返回默认的HttpResponseRedirect,从而使用新表单呈现页面。
保持表单的clean方法不变,然后将修改后的form.cleaned_data作为新示例化表单的初始dict传递。
forms.py

class CalculatorForm(forms.Form):
    body_weight = forms.FloatField(required=False)

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['body_weight'] is None:
            cleaned_data['body_weight'] = 50.0
        return cleaned_data

views.py

class CalculatorView(FormView):
    template_name = "myapp/mycalculator.html"
    form_class = CalculatorForm

    def get_context_data(self, res=None, **kwargs):
        context = super().get_context_data(**kwargs)
        if res is not None:
            context['result'] = res
        return context
    
    def form_valid(self, form):
        body_weight = form.cleaned_data["body_weight"]

        res = body_weight / 2

        form = self.form_class(initial=form.cleaned_data)
        return render(
            self.request, 
            self.template_name, 
            context=self.get_context_data(res=res, form=form, **kwargs)
        )

myapp/mycalculator.html

<body>
    <form action="{% url  'calculator' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Send</button>
    </form>
    {% if result %}
        <p>{{ result }}</p>
    {% endif %}
</body>

相关问题