我已經爲我的所有模型添加了「用戶」字段。當用戶創建一個對象,我想通過一個外鍵附上自己的身份證將django函數通用視圖轉換爲基於類的通用視圖
user = models.ForeignKey(User)
以前,我用create_object和update_object。我相信我需要切換到基於類的通用視圖,以便最輕鬆地將所需的用戶插入到記錄中。但是我很困惑我在調用create_object或update_object之前如何實現前一個函數中發生的一些預計算。
我有一個函數,處理所有的對象編輯,無論是創建或更新:
@login_required
def edit_item(request, modelname, submodelname=None, slug=None, id=None):
# Get parameter "next" to determine where to send user after object is created or updated
# Define which template to use
# Determine whether user is converting an object to another type
# Determine which form_class to use based on modelname and whether user is converting or not
# Redirect user if slug and id are not both correct
# Abort if user hit cancel instead of submit
# If object exists (slug and id are defined):
# Update_object with form_class, object_id, template_name, post_save_redirect, and extra_context
# Else
# Create_object with form_class, template_name, post_save_redirect, and extra_context
在基於類的通用視圖,如何/在哪裏/我什麼時候進行一些計算(邏輯周圍定義基於標準的模板或form_class)?我很困惑,因爲文檔似乎直來直去的定義:
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/'
難道我剛纔扔的邏輯呢?
class ContactView(FormView):
A = 1 + 2
if A == 3:
template_name = 'contact.html'
else:
template_name = 'contact_two.html'
form_class = ContactForm
success_url = '/thanks/'
?如何/我應該改變我的邏輯轉移到使用CreateView的或更新視圖VS什麼我在塞/ ID是否被定義使用create_object或update_object在根據同樣的功能在這裏做什麼?
爲什麼要轉換Django的功能?通用視圖不太方便。一大減是**繼承**而不是組合。創建自己的基於類的視圖或使用視圖函數更實際。 BTW通用視圖在最新的Django版本中已棄用。 – sergzach
您是否建議我創建基於類的基於視圖的基於類的視圖?我知道基於函數的create/update_object已被棄用,但我認爲它們正在被通用的基於類的視圖取代。 –
請原諒我的錯誤信息。任何方式,在使用基於類的通用視圖之前都要充分考慮。如果你想在繼承鏈的中間位置添加一個新類,那麼有時候會很痛苦。如果一個班級有幾個孩子,並且一個孩子必須具有新中間班級的特徵,而另一個孩子不具備該特徵,則需要重構。你必須在幾個功能中處理公共部分。在我的實踐中,它變得有點僵硬的結構。請看那邊:http://dpaste.com/hold/823122/ – sergzach