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,并且该表单无效,那么当模板呈现时,我认为所有其他字段都会消失。