Hi everyone,

Is there a way to assume one field to be invalid if another is? In the
form below, api_key can never be valid if location is not.

import urllib, urllib2

from django import forms
from websites.models import *

KEY_PARAM = 'key'

class WebsiteForm(forms.ModelForm):
  api_key = forms.CharField(label='API key')
  location = forms.URLField()

  class Meta:
    model = Website

  def clean_location(self):
    loc = self.cleaned_data.get('location')

    try:
      urllib2.urlopen(loc)
    except urllib2.URLError:
      raise forms.ValidationError('This location is inaccessible')

    return loc

  def clean_api_key(self):
    key = self.cleaned_data.get('api_key')
    loc = self.cleaned_data.get('location')

    if loc is None:
      raise forms.ValidationError(
        'Could not test key, the location is inaccessible'
      )

    try:
      urllib2.urlopen('%s%s?%s' % (loc, 'test/', urllib.urlencode({
        KEY_PARAM: key
      })))
    except urllib2.HTTPError:
      raise forms.ValidationError(
        'The API location rejects this key.'
      )

    return key


Thomas Allen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to