Ajax and ModelForm to Update a model
-
14-04-2021 - |
Вопрос
I'm trying to make updates to a model using Ajax/POST. I'd like to be able to just send the field being updated and not all fields in the Form. But this seems to cause the form to be invalid. Is there a good way to do this?
eg:
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
When updating the name I'd like to send a POST with this data
{'name': 'new name'}
as opposed to
{'name': 'new name', 'type':'existing type', 'owner': 'current owner'}
And likewise for updating type.
Is there a good way to do this?
Решение
Why don't you simply create a form -- say, AjaxUpdateNameForm
-- and then use django-ajax-validation to handle ajax requests?
Другие советы
It's not clear to me why you want to do this. I'm not sure that the efficiency saving of only sending the changed fields is worth the increased complexity of the view.
However, if you really want to do it, I would try overriding the get_form_class
method, and generating the model form class using request.POST
to determine the fields.
The following is untested.
# 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
Warning, this approach will have some quirks and might need some more hacking to work. If you did a regular, non-ajax POST for one field to this view, and the form was invalid, I think all the other fields would disappear when the template was rendered.