我在Django中編寫了一個Web應用程序,它以特定方式使用。它不是使用存儲在數據庫中的模型,而是使用REST API從其他應用程序和平臺收集的JSON數據動態構建表單。避免在Django基於類的視圖中重複
網頁呈現一個表單,其中顯示數學參數及其值的列表。然後用戶可以改變(或不改變)這些值,並按下「運行」按鈕來顯示一些計算結果。
表格是根據通過URL查詢JSON數據(給出參數列表及其初始值)獲得的數據構建的。根據規範,我必須使用Django並且不要使用數據庫來存儲任何參數值數據(唯一存儲的數據是JSON數據的URL地址)。
我結束了一些工作解決方案,使用CBV。我有一個DetailedView,該結構的:
class SimulationView(DetailView):
template_name='template.html'
model=SimModel # provides URLs for REST API (URLs for querying parameter list and simulation function)
# this is used to display the page with GET
def get_context_data(self, **kwargs):
# conn.request function that returns param_JSON in JSON/REST
# for a SUBSET of parameters in param_JSON build a list of entries named init_entries. Note not all parameters from the JSON request are used for the user interface.
# form = paramForm(initial=init_entries) and store in context['form']
return context
def post(self, request, *args, **kwargs):
# because the user may have changed parameter values, need to rebuild the JSON dataset to return to the URL with a simulation request
# conn.request function that returns param_list in JSON/REST
# for each param in JSON param_list build a list of entries
# form = paramForm(request.POST, request.FILES, initial=init_entries) and store in context['form']
# use form data to build REST request for the simulation function
# conn.request simulation function and get result in JSON
# store result in context['result']
return render(request, 'template.html', context)
template.html是reponsible做GET時同時顯示的初始形式,並做了POST當結果爲好。
正如您所見,存在性能問題。當您執行GET來構建頁面時,您必須執行REST連接來獲取數據並構建窗體和界面(這是正常的)。但是,當您POST請求模擬時,您需要再次運行URL連接以獲取JSON格式的參數列表,更改這些值,然後請求模擬結果。請注意,REST請求返回的參數比向用戶顯示的參數多得多,因此僅使用表單數據來構建適當的JSON請求是不可能的。這有效,但效率不高。我嘗試將param_JSON存儲在類的某個字段中,但這不起作用:執行POST時類再次被立即執行,並且param_JSON值丟失。
我需要一個get函數嗎?或者我是否完全錯誤?一般來說,有沒有更好的方法?非常感謝你的建議。
謝謝,這是一個有趣的建議。問題是:如果我不使用CBV,但FBV,即使在POST之後,我也會有同樣的問題重新創建我的動態表單?即使在顯示結果之後,我也需要再次顯示錶單,以便爲用戶提供相同的界面(並允許他再次從同一頁面運行模擬)。所以,即使我在view()函數中測試GET和POST的請求,我也不得不請求數據來構建我的界面。我對麼?或者你的意思是說,使用FBV,你可以將數據存儲在屬性中? – Zebulon