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 

私は

更新タイプの
{'name': 'new name', 'type':'existing type', 'owner': 'current owner'} 

、同様とは対照的に、このデータ

{'name': 'new name'} 

でPOSTを送信したいのですが。

これを行うには良い方法がありますか?

答えて

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 

警告このアプローチにはいくつかの癖があり、作業にはもう少しハッキングが必要な場合があります。このビューの1つのフィールドに対して通常の非Ajax POSTを行い、フォームが無効であった場合、テンプレートがレンダリングされると、他のフィールドはすべて消えてしまいます。

関連する問題