2012-12-01 34 views
3

我有一個模型,其中有一個作者ForeignKey,因爲這樣的:如何使用通用視圖在視圖中設置模型的字段?

class Appointment(models.Model): 
    # ... 
    author = models.ForeignKey(User) 

我想創建約會時,當前登錄用戶的author場被自動設定。換句話說,筆者領域不應該出現在我的窗體類:

class AppointmentCreateForm(ModelForm): 
    class Meta: 
     model = Appointment 
     exclude = ('author') 

有兩個問題:

  1. 如何訪問通用CreateView的形式,並設置author
  2. 如何判斷表單是否將排除的字段與從用戶輸入中讀取的值一起保存?

回答

2

我修改我的一般看法子這樣:

class AppointmentCreateView(CreateView):   
    model=Appointment 
    form_class = AppointmentCreateForm 

    def post(self, request, *args, **kwargs): 
     self.object = None 
     form_class = self.get_form_class() 
     form = self.get_form(form_class) 

     # the actual modification of the form 
     form.instance.author = request.user 

     if form.is_valid(): 
      return self.form_valid(form) 
     else: 
      return self.form_invalid(form) 

這裏有幾個重要的部分:

  • 我修改的形式instance領域,其中認爲回事實際模型被保存。
  • 當然,你可以擺脫我需要修改form_class
  • POST方法是兩班以上的層次,所以我需要納入基本代碼self.object = None線,合併超載並基於一個功能(我不打superpost)。

我認爲這是解決相當常見問題的好方法,而且我不必編寫自己的自定義視圖。

7

以下看起來稍微簡單一些。需要注意的是self.request獲取在View.as_view

class AppointmentCreateView(CreateView):   
    model=Appointment 
    form_class = AppointmentCreateForm 

    def get_form(self, form_class): 
     form = super(AppointmentCreateView, self).get_form(form_class) 
     # the actual modification of the form 
     form.instance.author = self.request.user 
     return form 
+1

正確的簽名設置woudn't是'高清get_form(個體經營,form_class ** =無**):'? –

+1

你是絕對正確的@AllanVital,它就像你從Django 1.8開始編寫的(當1.7版本出來時我停止使用Django) –

相關問題