【发布时间】:2019-08-07 12:36:39
【问题描述】:
我已经使用 ModelForm 和 FormView 成功地创建了一个包含很多字段的复杂表单。我设法保存了这些数据并将其显示在管理员中。因此,这只是我想做的事情的开始。
我的下一个目标是使用用户通过表单发布的输入对其执行计算,然后在另一个视图中显示这些计算的结果。
这样做的最佳方法是什么?到目前为止,这是我的文件(我不显示所有字段,因为它不相关)
这是我用来显示表单的视图
class SimulInputView(FormView):
form_class = SimulInputForm
template_name = 'apps/simulateur/formulaire/form.html'
success_url = reverse_lazy('simulateur_results')
def get_initial(self):
initial_data = super(SimulInputView, self).get_initial()
for key, value in dict_simul_form_default_data.items():
initial_data[key] = value
return initial_data
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['data'] = SimulateurData
return context
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super().form_valid(form)
我应该如何修改我的 form_valid 函数以使用另一个模块,该模块将对收到的表单数据执行计算,然后再将它们显示在另一个视图中?
编辑
我修改了我的代码如下。它似乎运作良好,但我想知道以这种方式处理它是否是一种好习惯。可以分享一下你的看法吗?
# VIEWS
class SimulInputView(FormView):
form_class = SimulInputForm
template_name = 'apps/simulateur/simulateur_form.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
# save form and put in data_instance to get its id later
data_instance = form.save()
# save form data
form_data = form.data
# call calculs_simulation.py script which performs calculations on form data
result = calculs_simulation(form_data)
# put results of calculation in SimulResult model, and set the id for SimulInput foreignkey
result_model = SimulResult(simulinput_id=data_instance.id, **result)
# save the result model and get its id
result_model.save()
result_model_id = result_model.id
return redirect('simulateur_results', result_model_id)
class SimulResultView(DetailView):
model = SimulResult
template_name = 'apps/simulateur/simulateur_results.html'
# URLS
urlpatterns = [
path('formulaire/', simul_input_views.SimulInputView.as_view(), name="simulateur_form"),
path('resultats/<int:pk>/', simul_result_views.SimulResultView.as_view(), name="simulateur_results"),
]
【问题讨论】:
标签: django django-forms