title: Custom validation on custom widget
body: <p>I have the following models (simplified):</p>
  
  <pre><code>class Location(models.Model):
      name = models.CharField(max_length=100)
      is_ok = models.BooleanField()
  
  class Profile(models.Model):
      name = models.CharField(max_length=100)
      location = models.ForeignKey(Location)
  
  class AnotherThing(models.Model):
      name = models.CharField(max_length=100)
      location = models.ForeignKey(Location)
  </code></pre>
  
  <p>I use a modelform to allow the users to add/edit <code>Profile</code> and <code>AnotherThing</code> items in the database.
  Simplified version:</p>
  
  <pre><code>class ProfileForm(ModelForm):
      class Meta:
          model = Profile
          widgets = {'location': CustomLocationWidget()}
  
  class AnotherThingForm(ModelForm):
      class Meta:
          model = Profile
          widgets = {'location': CustomLocationWidget()}
  </code></pre>
  
  <p>The simplified code for <code>CustomLocationWidget</code> is something like this:</p>
  
  <pre><code>class CustomLocationWidget(Input):
      def __init__(self, *args, **kwargs):
          super(CustomLocationWidget, self).__init__(*args, **kwargs)
  
      def render(self, name, value, attrs = None):
          output = super(CustomLocationWidget).render(name, value, attrs)
          output += 'Hello there!'
          return mark_safe(output)
  </code></pre>
  
  <p>As another validation I need to check that the <code>Location</code> has <code>is_ok == True</code> before saving. I can easily do this in the ModelForm for each item but the code is identical in each case and breaks DRY. How can I add it to each form without writing the code for it twice? Is it possible to attach the validator to the widget?</p>
  
  <p>I was looking at <a href="https://docs.djangoproject.com/en/1.3/ref/forms/validation/#using-validators" rel="nofollow">default_validators</a> but I don't know what other validators are used for <code>ForeignKey</code> fields and how to actually declare the validator.</p>