我想使用 django 表单,更新 POST 上的一些字段(到同一页面)并显示更新的字段值。这里不涉及数据库。
我有一个 Django 表单。我正在关注此处的文档https://docs.djangoproject.com/en/4.2/ref/forms/)
这是我的查看代码:
def QuestionView(request):
# if this is a POST request we need to process the form data
if request.method == "POST":
# create a form instance and populate it with data from the request:
form = QuestionForm(request.POST)
# check whether it's valid:
if form.is_valid():
query = form.data["question"]
result = chat(filepath=filepath, query=query)
form.cleaned_data["answer"] += query result["answer"]
form.cleaned_data["confidence_score"] = result["score"]
# if a GET (or any other method) we'll create a blank form
else:
form = QuestionForm()
return render(request, "home.html", {"form": form})`
这是我的表单代码:
class QuestionForm(forms.Form):
question = forms.CharField(label="Question", required=1, max_length=255)
answer = forms.CharField(label="Answer", required=0, max_length=16384)
confidence_score = forms.IntegerField(label="Confidence", required=0, min_value=0, max_value=100)```
线路
result = chat(filepath=filepath, query=query)
是一个成功返回值数组的外部函数。我可以成功地将这些值分配给 form.cleaned_data。
我无法将更新后的 clean_data 渲染回表单。
我是完全走错了路还是错过了一个重要的细节?
尝试使用 Django Forms 提交表单,更改一些值并回发到页面。 我期待更改后的值出现,但没有出现。
看起来您走在正确的轨道上,但您缺少一个关键步骤:使用修改后的数据更新表单的字段,然后将其渲染回响应中。您可以在实例化表单时使用初始属性设置表单的字段值。
以下是如何使用修改后的数据更新和呈现表单:
from django import forms
from django.shortcuts import render
from .your_module import chat # Import your chat function
def QuestionView(request):
if request.method == "POST":
form = QuestionForm(request.POST)
if form.is_valid():
query = form.cleaned_data["question"]
result = chat(filepath=filepath, query=query)
# Update form field values
form.fields["answer"].initial = result["answer"]
form.fields["confidence_score"].initial = result["score"]
else:
form = QuestionForm()
return render(request, "home.html", {"form": form})
在上面的代码中,在验证表单并从聊天功能获取结果后,我直接使用修改后的数据更新表单字段的初始属性。这样,当您渲染表单时,它将显示更新的值。
确保
result["answer"]
和 result["score"]
是可以分配给相应表单字段的有效值。
通过这些更改,您的表单在模板中呈现时应显示更新的字段值。