Ajax 和 ModelForm 更新模型
我正在尝试使用 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'}
更新类型。
有没有好的方法可以做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不简单地创建一个表单(例如
AjaxUpdateNameForm
),然后使用 django-ajax-validation 处理ajax请求?Why don't you simply create a form -- say,
AjaxUpdateNameForm
-- and then use django-ajax-validation to handle ajax requests?我不清楚你为什么要这样做。我不确定仅发送更改的字段所节省的效率是否值得增加视图的复杂性。
但是,如果您确实想这样做,我会尝试覆盖
get_form_class
方法,并使用request.POST
生成模型表单类来确定字段。以下未经测试。
警告,这种方法会有一些怪癖,可能需要更多的黑客才能工作。如果您对此视图的一个字段执行常规的非 ajax POST,并且表单无效,我认为渲染模板时所有其他字段都会消失。
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 usingrequest.POST
to determine the fields.The following is untested.
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.