Sunday, July 5, 2015

How to update a Django field which uses pre_save, within a pre_save hook?

I am using Django Markitup to store markdown rendered versions of TextFields in a database. I'd like to normalise all unicode data upon save using unicodedata.normalize.

I've written a pre_save signal hook, which does this on all TextFields and CharField and it works well.

@receiver(pre_save)  def unicode_normalise(sender, **kwargs):      obj = kwargs['instance']      fields = obj._meta.fields      for f in fields:          # excluding django markitup rendered fields          if f.name.endswith('_rendered'):              continue            if isinstance(f, MarkupField):              _markupfield = getattr(obj, f.name)              _markupfield.raw = normalize('NFC', getattr(obj, _markupfield.raw))              # would need to re-render and save rendered version here            elif isinstance(f, (models.CharField, models.TextField)):              normalized = normalize('NFC', getattr(obj, f.name))              setattr(obj, f.name, normalized)

But Django Markitup make things complicated, as it has this two field (raw, rendered) concept, which uses pre_save to render and save into it's hidden rendered field: GitHub source

My problem is that a field's pre_save has priority over the signal pre_save, so I cannot update the fields within the signal's pre_save function (comment inserted in code block above).

How can I re-run a field's pre_save function within my pre_save hook and make sure that the rendered markupfield is updated with the new version?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f7e781eb-9386-4177-a062-61cabc7a7cae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment