在数据库插入/更新之前处理字段
我有一个带有文本字段的 Django 模型。我在管理站点上使用富文本编辑器(nicEdit),以允许客户端轻松地将标记输入到字段中。我想在将任何内容插入数据库之前处理该字段的内容并执行一些操作。
例如,我想去除 MS Word、字体标签等生成的垃圾。我希望这部分应该很简单,但我不确定要覆盖或挂钩什么才能使其正常工作。
我还想检测远程链接的图像,将本地副本下载到 MEDIA_ROOT,并将 img src 重新链接到本地图像。我不太确定如何获取远程图像;我认为 django.Storage 可能会有所帮助,但看起来它无法从远程 URL 获取内容。
有什么建议吗?
I have a Django model with a text field. I'm using a rich text editor (nicEdit) on the admin site to allow the client to easily enter markup into the field. I'd like to process the contents of the field and perform a few actions before anything is inserted into the database.
For example, I want to strip junk generated by MS Word, font tags, etc. I hope this part should be easy, but I'm not sure what to override or hook to get this working.
I also want to detect remotely-linked images, download a local copy to MEDIA_ROOT, and relink the img src to the local image. I'm not quite sure how to go about fetching the remote image; I thought django.Storage
might help but it looks like it's unable to fetch content from a remote URL.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要在保存模型之前操作模型中的数据,请使用
save()
方法,例如:执行
super(modelname, self).save()
之前不会保存任何内容。如果您希望能够引发某种类型的错误,而不只是默默地处理它,您可能需要将
clean()
方法与raise ValidationError()
结合使用。下载远程内容对我来说是一项新任务,因此我无法为您提供帮助。您可能必须超越 Django 并找到 Python 函数来完成这项工作。
To manipulate data in your model before saving it, use the
save()
method like:Nothing will be saved until
super(modelname, self).save()
is executed.If you want the possibility of raising some type of error instead of just processing it silently, you'll probably want to use the
clean()
method withraise ValidationError()
.Downloading remote content is a new one for me, so I can't help you there. You might have to look past Django and find Python functions to do the job.
清除垃圾等应该使用自定义表单字段来完成。
下载图像...有多种方法可以解决该问题。
Stripping the junk and such should be done with a custom formfield.
Downloading the images... there are multiple ways to fix that problem.
这对我有用...
如果过程很简单,您可以将代码放在保存函数中,而不是函数调用
myCustomCleanFunction(self.text)
this work for me...
if the process is simple you can put the code in the save function instead of the function call
myCustomCleanFunction(self.text)