2012-11-27 122 views
3

我在Django 1.3中實現基於類的視圖,我發現自己在這種情況下,我的CreateView,UpdateView和DeleteView幾乎完全相同。有沒有一種方法來實現這隻有一個視圖CreateUpdateView或類似的東西,或者這是實現CBGV的標準方式?基於類的通用視圖和DRY

另外,在ThingyAdd中,我沒有指定像ThingyEdit那樣的模型,但它們都運行良好。我假設模型是由form_class的元部分ThingyForm定義的模型來暗示/拾取的,該模型是ModelForm。這個假設是否正確?

class ThingyAdd(AuthMixin, CreateView): 
    form_class = ThingyForm 
    context_object_name='object' 
    template_name='change_form.html' 
    success_url='/done/' 

class ThingyEdit(AuthMixin, UpdateView): 
    model = Thingy 
    form_class = ThingyForm 
    context_object_name='object' 
    template_name='change_form.html' 
    success_url='/done/' 

class ThingyDelete(AuthMixin, DeleteView): 
    model = Thingy 
    form_class = ThingyForm 
    context_object_name='object' 
    template_name='delete_confirmation.html' 
    success_url='/done/' 

回答

2

你可以創建另一個混入

class ThingyMixin(object): 
    model=Thingy 
    form_class=ThingyForm 
    template_name='change_form.html' 
    context_object_name='object' 
    success_url='/done/' 

然後在您的觀點:

class ThingyAdd(AuthMixin, ThingyMixin, CreateView): 
    pass 

class ThingyEdit(AuthMixin, ThingyMixin, UpdateView): 
    pass 

class ThingyDelete(AuthMixin, ThingyMixin, DeleteView): 
    template_name='delete_confirmation.html' 
+0

優秀的,謝謝。我是否甚至需要指定模型屬性,還是需要指定form_class上的模型? – scoopseven

+1

您應該只需要在DeleteView上提供模型屬性。 – czarchaic

相關問題