Electronics & Programming

develissimo

Open Source electronics development and programming

  • You are not logged in.
  • Root
  • » Django
  • » Validation of dependent form fields [RSS Feed]

#1 June 14, 2010 19:26:09

Thomas A.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Validation of dependent form fields


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 athttp://groups.google.com/group/django-users?hl=en.

Offline

#2 June 14, 2010 19:31:24

Dennis K.
Registered: 2009-11-02
Reputation: +  0  -
Profile   Send e-mail  

Validation of dependent form fields


On ma, 2010-06-14 at 11:26 -0700, Thomas Allen wrote:

> 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.

The place to implement such checks is in the clean() method of the form,
which is called after all the individual clean_* methods.
--
Dennis K.

They've gone to plaid!

--
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 athttp://groups.google.com/group/django-users?hl=en.

Offline

Board footer

Moderator control

Enjoy the 19th of October
PoweredBy

The Forums are managed by develissimo stuff members, if you find any issues or misplaced content please help us to fix it. Thank you! Tell us via Contact Options
Leave a Message
Welcome to Develissimo Live Support