def search(request): form = SearchForm(request.GET) context = { 'form': form, } if form.is_valid(): query_text = form.cleaned_data['q'] context['query'] = query_text postcode = ''.join(query_text.split()).upper() if validation.is_valid_postcode(postcode): res = requests.get('https://api.postcodes.io/postcodes/' + postcode, timeout=1) if res.ok: result = res.json()['result'] point = Point(result['longitude'], result['latitude'], srid=4326) bbox = Polygon.from_bbox((point.x - .05, point.y - .05, point.x + .05, point.y + .05)) context['postcode'] = Locality.objects.filter( latlong__within=bbox).filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True)).distinct( ).annotate(distance=Distance('latlong', point) ).order_by('distance').defer('latlong')[:2] if 'postcode' not in context: query = SearchQuery(query_text, search_type="websearch", config="english") rank = SearchRank(F('search_vector'), query) localities = Locality.objects.filter() operators = Operator.objects.filter( service__current=True).distinct() services = Service.objects.filter(current=True) localities = localities.filter(search_vector=query).annotate( rank=rank).order_by('-rank') operators = operators.filter(search_vector=query).annotate( rank=rank).order_by('-rank') services = services.filter(search_vector=query).annotate( rank=rank).order_by('-rank') services = services.prefetch_related('operator') context['localities'] = Paginator(localities, 20).get_page( request.GET.get('page')) context['operators'] = Paginator(operators, 20).get_page( request.GET.get('page')) context['services'] = Paginator(services, 20).get_page( request.GET.get('page')) return render(request, 'search.html', context)
def LocationPosition(request): """ Get coordinates for location or postcode """ locationtext = request.GET.get('location').strip() location, zoom, result = None, 15, {'result': 'failure'} postcodetext = re.sub("[^0-9a-zA-Z]+", "", locationtext).upper() if validation.is_valid_postcode(postcodetext): location = get_postcode_point(postcodetext) else: locationrecord = Location.objects.filter( town__iexact=locationtext).first() if (locationrecord is not None): location = locationrecord.location zoom = locationrecord.scale if location: result = { 'result': 'success', 'data': { 'lat': location[1], 'lng': location[0], 'zoom': zoom } } return HttpResponse(json.dumps(result), content_type="text/json-comment-filtered")
def clean(self): cleaned_data = super(OrganisationFinderForm, self).clean() location = cleaned_data.get('location', None) if location: postcode = re.sub('\s+', '', location.upper()) if validation.is_valid_postcode(postcode): organisations = self.organisations_from_postcode(postcode) validation_message = "Sorry, there are no matches within 5 miles of %s. Please try again. %s" % (location, self.PILOT_SEARCH_CAVEAT) elif validation.is_valid_partial_postcode(postcode): organisations = self.organisations_from_postcode(postcode, partial=True) validation_message = "Sorry, there are no matches within 5 miles of %s. Please try again. %s" % (location, self.PILOT_SEARCH_CAVEAT) else: organisations = self.queryset.filter(name__icontains=location) if len(organisations) < 5: # Try a metaphone search to give more results location_metaphone = dm(location) # First do a __startswith or __endswith alt_orgs = self.queryset.filter(Q(name_metaphone__startswith=location_metaphone[0]) | Q(name_metaphone__endswith=location_metaphone[0]), ~Q(pk__in=list([a.id for a in organisations]))) organisations = list(chain(organisations, alt_orgs)) if len(organisations) < 10: # Try a metaphone __contains to give even more results more_orgs = self.queryset.filter(Q(name_metaphone__contains=location_metaphone[0]), ~Q(pk__in=list([a.id for a in organisations]))) organisations = list(chain(organisations, more_orgs)) validation_message = "We couldn't find any matches for '%s'. Please try again. %s" % (location, self.PILOT_SEARCH_CAVEAT) if len(organisations) == 0: raise forms.ValidationError(validation_message) cleaned_data['organisations'] = organisations return cleaned_data
def clean(self): cleaned_data = super(PostcodeFieldForm, self).clean() postcode_field = cleaned_data.get('postcode_field') skip_bad_rows = cleaned_data.get('skip_bad_rows') bad_rows = 0 bad_row_numbers = [] for i, row in enumerate(self.instance.original_file_reader()): postcode = row[postcode_field].replace(" ", "") if not is_valid_postcode(postcode): bad_rows += 1 bad_row_numbers.append(str(i + 1)) if not skip_bad_rows and bad_rows > 0: # Make sure the skip checkbox is shown next time self.fields['skip_bad_rows'].widget = forms.CheckboxInput() if bad_rows == 1: msg = 'Row: ' msg += ', '.join(bad_row_numbers) msg += ' doesn\'t seem to be a valid postcode.' msg += ' Do you want us to skip it?' else: msg = 'Rows: ' msg += ', '.join(bad_row_numbers) msg += ' don\'t seem to be valid postcodes.' msg += ' Do you want us to skip them?' raise forms.ValidationError(msg) else: cleaned_data['bad_rows'] = bad_rows return cleaned_data
def validate_uk_postcode(value): # The validator doesn't like spaces or lowercase: test_value = value.replace(' ', '').upper() if validation.is_valid_postcode(test_value) is False: raise ValidationError( _('%(value)s is not a valid postcode'), params={'value': value}, )
def getvalidPostcode(): userText = request.args.get('msg') postcode.append(userText) postcode_without_space = userText.replace(" ", "") if (validation.is_valid_postcode(postcode_without_space) and " " in userText): return "1" else: return "2"
def add_helper(request): postcode = request.POST["postcodeFirst"] + request.POST["postcodeSecond"] if validation.is_valid_postcode(postcode): Helper.objects.create( postcodeFirst=request.POST["postcodeFirst"], postcodeSecond=request.POST["postcodeSecond"], link=request.POST["link"], ) return render(request, "thankyou.html") else: return render(request, "error.html", {"postcode": postcode})
def clean_postcode(self) -> str: """If country is in the UK, validates a UK postcode, and reformats it to uppercase with the correct space""" country = self.cleaned_data.get('country') postcode = self.cleaned_data.get('postcode') if postcode and country and 'United Kingdom' in country.name: spaceless_postcode = re.sub(r'\s', '', postcode).upper() if not is_valid_postcode(spaceless_postcode): raise ValidationError('Invalid UK postcode') postcode = f'{spaceless_postcode[:-3]} {spaceless_postcode[-3:]}' return postcode
def postcodeSearch(postcode): postcode_id = postcode.replace(' ','').upper() if validation.is_valid_postcode(postcode_id): searchQuery = { "query": { "ids" : { "type" : "postcode", "values" : postcode_id } } } return requests.get(ES_URL,json=searchQuery).json() else: return False #return false for invalid postcode
def get_postcode(self): q = self.cleaned_data['q'] q = ''.join(q.split()).upper() if validation.is_valid_postcode(q): res = session.get('https://api.postcodes.io/postcodes/' + q, timeout=2) if not res.ok: return '' result = res.json()['result'] point = Point(result['longitude'], result['latitude'], srid=4326) bbox = Polygon.from_bbox((point.x - .05, point.y - .05, point.x + .05, point.y + .05)) return Locality.objects.filter( latlong__within=bbox ).filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True) ).distinct().annotate( distance=Distance('latlong', point) ).order_by('distance').defer('latlong')[:2]
def validate_postcode(postcode: str): """ Validate UK postcode format Args: postcode: string Raises: Validation Error: Returns: None: """ postcode_no_spaces = postcode.replace(' ', '') if not validation.is_valid_postcode(postcode_no_spaces): raise ValidationError( 'This cannot be a valid postcode: %s' % postcode)
def get_postcode(self): q = self.cleaned_data['q'] q = ''.join(q.split()).upper() if validation.is_valid_postcode(q): res = session.get('https://api.postcodes.io/postcodes/' + q, timeout=2) if not res.ok: return '' result = res.json()['result'] point = Point(result['longitude'], result['latitude'], srid=4326) bbox = Polygon.from_bbox( (point.x - .05, point.y - .05, point.x + .05, point.y + .05)) return Locality.objects.filter(latlong__within=bbox).filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True)).distinct().annotate( distance=Distance('latlong', point)).order_by( 'distance').defer('latlong')[:2]
def validate_postcode(form, field): #is it a postcode? if not validation.is_valid_postcode(field.data.replace(' ', '').upper()): raise ValidationError('You need to enter a valid postcode') if app.config.get('BECKTON_POSTCODE_AREAS_CSV', False): #is it in the an allowed postcode? condition_postcode_areas = app.config['BECKTON_POSTCODE_AREAS_CSV'].split(',') if not condition_postcode_areas == []: in_bounds = False for postcode_area in condition_postcode_areas: if field.data.lower().startswith(postcode_area.lower()): in_bounds = True if not in_bounds: postcode_areas_formatted = ', '.join(condition_postcode_areas) raise ValidationError('You can currently only sign up if your postcode starts with %s' % postcode_areas_formatted)
def get_context_data(self, **kwargs): context = super(MapSearch, self).get_context_data() term = self.request.GET.get('term', '') # no search, no results if not len(term): return context to_serialize = context['results'] # Check if the term is a postcode possible_postcode = re.sub('\s+', '', term.upper()) is_postcode = is_valid_postcode(possible_postcode) is_partial_postcode = is_valid_partial_postcode(possible_postcode) if is_postcode or is_partial_postcode: try: point = MapitPostCodeLookup.postcode_to_point(possible_postcode, partial=is_partial_postcode) to_serialize.append({ "id": possible_postcode, "text": term.upper() + ' (postcode)', "type": "place", "lat": point.y, "lon": point.x, }) return context except MapitError: # Not really much to be done about an error, pass through to the rest of the code. pass places = Place.objects.filter(name__istartswith=term) places = places.order_by('name') for obj in places[:8]: to_serialize.append({ "id": obj.id, "text": obj.context_name, "type": "place", "lat": obj.centre.y, "lon": obj.centre.x, }) return context
def process(userText): postcode_without_space = postcode[0].replace(" ", "") if (validation.is_valid_postcode(postcode_without_space) and " " in postcode[0]): if (num[0] == 2): response = hack.getMeATM(postcode[0]) return response elif (num[0] == 1): if (userText == "no" or userText == "No"): response = hack.getMeBranches(postcode[0]) return response else: try: response = hack.getMeBranchesForSpecificBank( postcode[0], userText) return response except: return ("Invalid bank input") else: return ("Invalid Postcode.")
def api(): postcode = request.args.get('postcode', '') postcode = postcode.replace(' ', '').upper() if postcode == '' or not validation.is_valid_postcode(postcode): return Response(response="{'message': 'Invalid data'}", status=400, mimetype='application/json') data = {} br = mechanize.Browser() br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] try: br.open(app.config['DIRECT_GOV_URL']) br.form = list(br.forms())[0] br.form["ctl00$ContentPlaceHolder1$Postcode"] = postcode response = br.submit() html = response.read() except urllib2.URLError: return Response(response="{'message': 'Bad gateway - direct.gov.uk not available'}", status=502, mimetype='application/json') try: #get name matches = re.findall('<h3>([^<]*)</h3>', html) name = matches[1].strip() #get address matches = re.search('(.*)<br \/>Telephone', html) print matches parts = matches.group(1).strip().split('<br />') postcode = parts[len(parts) - 1] address = ', '.join(parts) except IndexError: return Response(response="{'message': 'Bad gateway - error passing data'}", status=502, mimetype='application/json') data = {'name': name, 'address':address, 'postcode':postcode, 'opening-times': []} return Response(response=json.dumps(data), status=200, headers=None, mimetype='application/json', content_type=None, direct_passthrough=False)
def checkout(request): customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) products = order.orderproduct_set.all() cartProducts = order.get_cart_items if request.method == 'GET': form = CheckoutForm() context = { 'products': products, 'order': order, 'cartProducts': cartProducts, 'form': form } return render(request, 'checkout.html', context) form = CheckoutForm(request.POST) context = { 'products': products, 'order': order, 'cartProducts': cartProducts, 'form': form } if not form.is_valid(): return render(request, 'checkout.html', context) name = form.cleaned_data['name'].strip() street_address = form.cleaned_data['street_address'].strip() city = form.cleaned_data['city'].strip() state = form.cleaned_data['state'].strip() postcode = form.cleaned_data['postcode'].strip().upper() phone_number = form.cleaned_data['phone_number'].strip() postcode = ''.join(postcode.split()) if len(phone_number) != 11: messages.warning(request, 'Please enter a valid phone number') return render(request, 'checkout.html', context) if not phone_number.isdecimal(): messages.warning(request, 'Please enter a valid phone number') return render(request, 'checkout.html', context) if not validation.is_valid_postcode(postcode): messages.warning(request, 'Please enter a valid postcode') return render(request, 'checkout.html', context) order.order_date = datetime.datetime.today().strftime('%Y-%m-%d') order.order_id = datetime.datetime.now().timestamp() order.complete = True order.save() new_shipping = Shipping(customer=customer, order=order, street_address=street_address, city=city, state=state, postcode=postcode, phone_number=phone_number) new_shipping.save() messages.success(request, f'Thanks for your order') return HttpResponseRedirect('/')
def is_valid_postcode(pc): return validation.is_valid_postcode( pc, SPECIAL_POSTCODES + ('ZZ99ZZ', 'ZZ99ZY'))
def is_valid_postcode(value): if not validation.is_valid_postcode(value.replace(' ', '').upper()): raise ValidationError(_('Please enter a UK postcode'))
def post_code_validator(form, field): if not validation.is_valid_postcode(field.data): raise ValidationError('Invalid UK Post Code')
def is_valid_postcode(pc): return validation.is_valid_postcode(pc, SPECIAL_POSTCODES + ('ZZ99ZZ', 'ZZ99ZY'))
def f(postcode): if not is_valid_postcode(postcode, extra_postcodes_that_are_valid): raise Invalid("Postcode is invalid: " + postcode) return postcode