title: How to save XML safe text data to DB using Django models?
body: <p>I am building a Django site that interfaces with database that supposed to save XML safe data only. A string like <em>"Mike &amp; Ike"</em> needs to be stored as <em>"Mike &amp;amp; Ike"</em></p>
  
  <p>From what I can see there is two approaches to this. I can convert string to XML safe string when validating my forms. For every field that can contain text data I would have to call <code>xml.sax.saxutils.escape</code> in appropriate validating function. In addition when supplying initial data from DB models to my form objects I have to mark strings as <strong>safe</strong> using <code>django.utils.safestring.mark_safe</code> function (template filters like <strong>|safe</strong> and <strong>autoescape off</strong> do not help here, because form's html output automatically escapes all values).</p>
  
  <pre><code>class NameForm(forms.Form):
      name = forms.CharField()
  
      def clean_name(self):
          from xml.sax.saxutils import escape
          return escape(self.cleaned_data['name'])
  
  from django.utils.safestring import mark_safe
  form = NameForm(initial={'name': mark_safe(Customer.objects.get(pk=1).name)})
  </code></pre>
  
  <p>There is downside to this approach. The string may considerably change after being <code>escape</code>d. Plus I have to remember to mark safe all initial values. I think a better approach would be to escape values at the time of database save, just before values are written to database. It will let me assign any values directly to model object and not worry about escaping them. Also, when object is looked up from database like <code>c = Customer.objects.get(pk=1)</code> the value <code>c.name</code> should be unescaped value. For example:</p>
  
  <pre><code>c = Customer(id=1, name="Mike &amp; Ike")
  c.full_clean() # "test drive" escaping here and make sure it does not cause field overflow
  c.save()
  # database now have
  # CUSTOMER
  # NAME: 'Mike &amp;amp; Ike'
  c1=Customer.objects.get(pk=1)
  c1.name # Mike &amp; Ike
  c.name  # Mike &amp; Ike
  </code></pre>
  
  <p>Is that possible? Where do I start? I have read <a href="https://docs.djangoproject.com/en/1.4/ref/models/instances/#what-happens-when-you-save" rel="nofollow">Django documentation</a> and it talks about steps that are done when data is saved but there is no guide on how to customize that behaviour. I think I want to customize step 3 mentioned there, but I am open to suggestions. Any help is appreciated.</p>