Ejemplo n.º 1
0
    def clean_postcode(self):
        code = self.cleaned_data['postcode']
        if not POSTCODE_RE.match(code):
            raise forms.ValidationError("Please enter a valid postcode")
        try:
            constituency_name = twfy.getConstituency(code)
        except (IOError, ValueError): # ValueError may be thrown by
                                      # JSON decoding                                      
            raise forms.ValidationError("Sorry, there was a problem connecting to TheyWorkForYou to look up your constituency. Please try again in a few minutes.")

        if constituency_name:
            constituency = Constituency.objects.all()\
                           .filter(name=constituency_name)\
                           .filter(year=CONSTITUENCY_YEAR)
            if constituency:
                self.cleaned_data['constituency'] = constituency[0]
            else:
                raise forms.ValidationError("Internal error: Constituency '%s', year '%s' not found in DemocracyClub database" % (constituency_name, CONSTITUENCY_YEAR))
        else:
            raise forms.ValidationError("Unknown postcode")
        return code
Ejemplo n.º 2
0
def constituency(place):
    try:
        if POSTCODE_RE.match(place):
            const = twfy.getConstituency(place)
            if const == None:
                return None
            else:
                return [const]
        else:
            _, (lat, lng) = geocode(place)
            
            consts = None
            distance = 10
            while not consts:
                # Only likely to actually loop in extreme, circumstances,
                # e.g. "Haltwhistle". See issue 19
                consts = twfy.getConstituencies(latitude=lat,
                                                longitude=lng,
                                                distance=distance)
                distance = distance * 2
            
            return [x['name'] for x in consts]
    except Exception:
        return None