3

我想使用Ajax/POST對模型進行更新。我希望能夠發送正在更新的字段,而不是表單中的所有字段。但是這似乎導致表單無效。有沒有一個好的方法來做到這一點?Ajax和ModelForm更新模型

如:

class Video(models.Model): 
    name = models.CharField(max_length=100) 
    type = models.CharField(max_length=100) 
    owner = models.ForeignKey(User, related_name='videos') 
    ... 
    #Related m2m fields 
    .... 

class VideoForm(modelForm): 
    class Meta: 
     model = Video 
     fields = ('name', 'type', 'owner') 

class VideoCreate(CreateView): 
    template_name = 'video_form.html' 
    form_class = VideoForm 
    model = Video 

當更新的名字,我想發送POST與此數據

{'name': 'new name'} 

,而不是

{'name': 'new name', 'type':'existing type', 'owner': 'current owner'} 

27:11更新類型。

有沒有很好的方法來做到這一點?

回答

0

爲什麼不簡單地創建一個表單 - 例如AjaxUpdateNameForm - 然後用django-ajax-validation來處理ajax請求?

0

我不清楚你爲什麼要這樣做。我不確定只發送更改字段的效率節省是否值得增加視圖的複雜性。

但是,如果您確實想這樣做,我會嘗試覆蓋get_form_class方法,並使用request.POST生成模型表單類以確定字段。

以下是未經測試的。

# in your question you are subclassing CreateView, but 
# surely you want UpdateView if you are changing details. 
class VideoCreate(UpdateView): 
    template_name = 'video_form.html' 
    model = Video 

    get_form_class(self): 
     """ 
     Only include posted fields in the form class 
     """ 
     model_field_names = self.model._meta.get_all_field_names() 
     # only include valid field names 
     form_field_names = [k for k in request.POST if k in model_field_names] 

     class VideoForm(modelForm): 
      class Meta: 
       model = Video 
       fields = form_field_names 

     return VideoForm 

警告,這種方法會有一些怪癖,可能需要一些更多的黑客工作。如果您爲該視圖的一個字段執行了常規的非ajax POST,並且該表單無效,那麼當模板呈現時,我認爲所有其他字段都會消失。