【问题标题】:Ajax and ModelForm to Update a modelAjax 和 ModelForm 更新模型
【发布时间】:2012-02-02 15:08:53
【问题描述】:

我正在尝试使用 Ajax/POST 对模型进行更新。我希望能够只发送正在更新的字段,而不是表单中的所有字段。但这似乎导致表单无效。有什么好办法吗?

例如:

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'}

同样用于更新类型。

有什么好办法吗?

【问题讨论】:

    标签: django django-models django-forms django-class-based-views


    【解决方案1】:

    你为什么不简单地创建一个表单——比如AjaxUpdateNameForm——然后使用django-ajax-validation来处理ajax请求?

    【讨论】:

      【解决方案2】:

      我不清楚你为什么要这样做。我不确定仅发送更改的字段所节省的效率是否值得增加视图的复杂性。

      但是,如果您真的想这样做,我会尝试覆盖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,并且表单无效,我认为在呈现模板时所有其他字段都会消失。

      【讨论】:

        猜你喜欢
        • 2014-03-03
        • 1970-01-01
        • 2021-10-03
        • 2011-01-15
        • 1970-01-01
        • 2015-12-22
        • 2013-08-23
        • 2017-04-18
        • 2021-03-03
        相关资源
        最近更新 更多