def create_textinput(self, name, field, value, **extra_attrs): '''Generate and render a :class:`django.forms.widgets.TextInput` for a single year, month, or day input. If size is specified in the extra attributes, it will also be used to set the maximum length of the field. :param name: base name of the input field :param field: pattern for this field (used with name to generate input name) :param value: initial value for the field :param extra_attrs: any extra widget attributes :returns: rendered HTML output for the text input ''' # TODO: move id-generation logic out for re-use if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name # use size to set maximum length if 'size' in extra_attrs: extra_attrs['maxlength'] = extra_attrs['size'] local_attrs = self.build_attrs(id=field % id_, **extra_attrs) txtinput = TextInput() return txtinput.render(field % name, value, local_attrs)
def render(self, name, value, attrs=None): output = [] textinput = TextInput(attrs={"class": "dateselector"}) if isinstance(value, datetime.datetime) or isinstance(value, datetime.date): value = value.strftime("%d/%m/%Y") output.append(textinput.render(name, value, attrs)) return mark_safe("".join(output))
def render(self, name, value, attrs=None): output = [] textinput = TextInput(attrs={"class": "dateselector"}) if isinstance(value, datetime.datetime) or isinstance(value, datetime.date): value = value.strftime("%d/%m/%Y") output.append(textinput.render(name, value, attrs)) return mark_safe(''.join(output))
class MapWidget(BaseContainerWidget): def __init__(self, data_widget, attrs=None): self.key_widget = TextInput() self.key_widget.is_localized = self.is_localized super(MapWidget, self).__init__(data_widget, attrs) def render(self, name, value, attrs=None): if value is not None and not isinstance(value, dict): raise TypeError("Value supplied for %s must be a dict." % name) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) fieldset_attr = {} # in Python 3.X dict.items() returns dynamic *view objects* value = list(value.items()) value.append(('', '')) for i, (key, widget_value) in enumerate(value): if id_: fieldset_attr = dict( final_attrs, id='fieldset_%s_%s' % (id_, i) ) group = [] if not self.is_hidden: group.append( mark_safe('<fieldset %s>' % flatatt(fieldset_attr))) if id_: final_attrs = dict(final_attrs, id='%s_key_%s' % (id_, i)) group.append(self.key_widget.render( name + '_key_%s' % i, key, final_attrs) ) if id_: final_attrs = dict(final_attrs, id='%s_value_%s' % (id_, i)) group.append(self.data_widget.render( name + '_value_%s' % i, widget_value, final_attrs) ) if not self.is_hidden: group.append(mark_safe('</fieldset>')) output.append(mark_safe(''.join(group))) return mark_safe(self.format_output(output)) def value_from_datadict(self, data, files, name): i = 0 ret = {} while (name + '_key_%s' % i) in data: key = self.key_widget.value_from_datadict( data, files, name + '_key_%s' % i ) value = self.data_widget.value_from_datadict( data, files, name + '_value_%s' % i ) if key not in EMPTY_VALUES: ret.update(((key, value), )) i = i + 1 return ret def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = super(MapWidget, self)._get_media() media = media + self.key_widget.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super(MapWidget, self).__deepcopy__(memo) obj.key_widget = copy.deepcopy(self.key_widget) return obj
class MapWidget(Widget): """ A widget that is composed of multiple widgets. Its render() method is different than other widgets', because it has to figure out how to split a single value for display in multiple widgets. The ``value`` argument can be one of two things: * A list. * A normal value (e.g., a string) that has been "compressed" from a list of values. In the second case -- i.e., if the value is NOT a list -- render() will first "decompress" the value into a list before rendering it. It does so by calling the decompress() method, which MultiWidget subclasses must implement. This method takes a single "compressed" value and returns a list. When render() does its HTML rendering, each value in the list is rendered with the corresponding widget -- the first value is rendered in the first widget, the second value is rendered in the second widget, etc. Subclasses may implement format_output(), which takes the list of rendered widgets and returns a string of HTML that formats them any way you'd like. You'll probably want to use this class with MultiValueField. """ def __init__(self, contained_widget, attrs=None): self.key_widget = TextInput() self.key_widget.is_localized = self.is_localized if isinstance(contained_widget, type): contained_widget = contained_widget() self.data_widget = contained_widget self.data_widget.is_localized = self.is_localized super(MapWidget, self).__init__(attrs) def render(self, name, value, attrs=None): if value is not None and not isinstance(value, dict): raise TypeError("Value supplied for %s must be a dict." % name) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) fieldset_attr = {} value = list(value.items( )) # in Python 3.X dict.items() returns dynamic *view objects* value.append(('', '')) for i, (key, widget_value) in enumerate(value): if id_: fieldset_attr = dict(final_attrs, id='fieldset_%s_%s' % (id_, i)) group = [] group.append(mark_safe('<fieldset %s>' % flatatt(fieldset_attr))) if id_: final_attrs = dict(final_attrs, id='%s_key_%s' % (id_, i)) group.append( self.key_widget.render(name + '_key_%s' % i, key, final_attrs)) if id_: final_attrs = dict(final_attrs, id='%s_value_%s' % (id_, i)) group.append( self.data_widget.render(name + '_value_%s' % i, widget_value, final_attrs)) group.append(mark_safe('</fieldset>')) output.append(mark_safe(''.join(group))) return mark_safe(self.format_output(output)) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += '_0' return id_ def value_from_datadict(self, data, files, name): i = 0 ret = {} while (name + '_key_%s' % i) in data: key = self.key_widget.value_from_datadict(data, files, name + '_key_%s' % i) value = self.data_widget.value_from_datadict( data, files, name + '_value_%s' % i) if key not in EMPTY_VALUES: ret.update(((key, value), )) i = i + 1 return ret def format_output(self, rendered_widgets): """ Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot. This hook allows you to format the HTML design of the widgets, if needed. """ return ''.join(rendered_widgets) def _get_media(self): "Media for a multiwidget is the combination of all media of the subwidgets" media = Media() for w in self.widgets: media = media + w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super(MapWidget, self).__deepcopy__(memo) obj.key_widget = copy.deepcopy(self.key_widget) obj.data_widget = copy.deepcopy(self.data_widget) return obj
class MapWidget(Widget): """ A widget that is composed of multiple widgets. Its render() method is different than other widgets', because it has to figure out how to split a single value for display in multiple widgets. The ``value`` argument can be one of two things: * A list. * A normal value (e.g., a string) that has been "compressed" from a list of values. In the second case -- i.e., if the value is NOT a list -- render() will first "decompress" the value into a list before rendering it. It does so by calling the decompress() method, which MultiWidget subclasses must implement. This method takes a single "compressed" value and returns a list. When render() does its HTML rendering, each value in the list is rendered with the corresponding widget -- the first value is rendered in the first widget, the second value is rendered in the second widget, etc. Subclasses may implement format_output(), which takes the list of rendered widgets and returns a string of HTML that formats them any way you'd like. You'll probably want to use this class with MultiValueField. """ def __init__(self, widget_type, attrs=None): self.widget_type = widget_type self.key_widget = TextInput() self.key_widget.is_localized = self.is_localized self.data_widget = self.widget_type() self.data_widget.is_localized = self.is_localized super(MapWidget, self).__init__(attrs) def render(self, name, value, attrs=None): if value is not None and not isinstance(value, dict): raise TypeError("Value supplied for %s must be a dict." % name) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) fieldset_attr = {} value = list(value.items()) # in Python 3.X dict.items() returns dynamic *view objects* value.append(('', '')) for i, (key, widget_value) in enumerate(value): if id_: fieldset_attr = dict(final_attrs, id='fieldset_%s_%s' % (id_, i)) group = [] group.append(mark_safe('<fieldset %s>' % flatatt(fieldset_attr))) if id_: final_attrs = dict(final_attrs, id='%s_key_%s' % (id_, i)) group.append(self.key_widget.render(name + '_key_%s' % i, key, final_attrs)) if id_: final_attrs = dict(final_attrs, id='%s_value_%s' % (id_, i)) group.append(self.data_widget.render(name + '_value_%s' % i, widget_value, final_attrs)) group.append(mark_safe('</fieldset>')) output.append(mark_safe(''.join(group))) return mark_safe(self.format_output(output)) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += '_0' return id_ def value_from_datadict(self, data, files, name): i = 0 ret = {} while (name + '_key_%s' % i) in data: key = self.key_widget.value_from_datadict(data, files, name + '_key_%s' % i) value = self.data_widget.value_from_datadict(data, files, name + '_value_%s' % i) if key not in EMPTY_VALUES: ret.update(((key, value), )) i = i + 1 return ret def format_output(self, rendered_widgets): """ Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot. This hook allows you to format the HTML design of the widgets, if needed. """ return ''.join(rendered_widgets) def _get_media(self): "Media for a multiwidget is the combination of all media of the subwidgets" media = Media() for w in self.widgets: media = media + w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super(MapWidget, self).__deepcopy__(memo) obj.widget_type = copy.deepcopy(self.widget_type) obj.key_widget = copy.deepcopy(self.key_widget) obj.data_widget = copy.deepcopy(self.data_widget) return obj
class LocationWidget(Widget): DEFAULT_WIDTH = 500 DEFAULT_HEIGHT = 300 def __init__(self, *args, **kwargs): self.dynamic_loc = "true" if kwargs.has_key("dynamic_loc"): self.dynamic_loc = kwargs.pop("dynamic_loc", "true") self.map_width = kwargs.pop("map_width", self.DEFAULT_WIDTH) self.map_height = kwargs.pop("map_height", self.DEFAULT_HEIGHT) super(LocationWidget, self).__init__(*args, **kwargs) self.inner_widget = TextInput(attrs=kwargs.get('attrs')) def render(self, name, value, *args, **kwargs): if not value: value = settings.GEO_LOCATION if isinstance(value, unicode): a, b = value.split(',') else: a, b = value.split(',') lat, lng = float(a), float(b) js = ''' <script type="text/javascript"> var $loadingIndicator = $('<img/>').attr({ 'id': 'ajaxloader', 'src': '/site_media/images/loading.gif', 'alt': 'Obtaining your location. Please wait.', 'style': 'border: 1px solid #fff;margin: 0 10px 0 0' }) .addClass('loader'); var loading_div = null; var use_dynamic_loc = %(useDynamicLocation)s; var defaultLocation = {lat: 41.83587795000, lng: -87.62874322666}; var geo_accuracy = 60; var geo_options = { timeout: 12000, maximumAge: 6000, enableHighAccuracy: false }; function geoSuccess(position) { } function geoError(error) { switch(error.code) { case error.PERMISSION_DENIED: alert("user did not share geolocation data"); break; case error.POSITION_UNAVAILABLE: alert("could not detect current position"); break; case error.TIMEOUT: // alert("retrieving position timed out"); $('#loading').html("geolocation failed! using default location", function() {}); initializeLocation(defaultLocation); $('#loading').slideUp('slow', function() { $('#map_%(name)s').slideDown('slow'); }); break; default: alert("unknown error"); break; } } function getCurrentLocation() { var location; if (use_dynamic_loc==true && navigator.geolocation) { console.log('loading'); $('#loading').html($loadingIndicator); //$('#loading').slideDown('slow', function() { $('<span id="feedback">Obtaining GPS co-ordinates...</span>').insertAfter('#ajaxloader'); //}); navigator.geolocation.getCurrentPosition(function(position) { //console.log('Your lat-long is: ' + position.coords.latitude + ' / ' + position.coords.longitude); //console.log('You live in '+position.address.city +', '+position.address.streetNumber+', '+position.address.street); console.log('Accuracy: ' + position.coords.accuracy); console.log('Altitude Accuracy: ' + position.coords.altitudeAccuracy); geo_accuracy = position.coords.accuracy; location = { lat: position.coords.latitude, lng: position.coords.longitude }; $('#feedback').html('Loading map...'); initializeLocation(location); $('#loading').slideUp('slow', function() { $('#map_%(name)s').slideDown('slow'); }); }, geoError, geo_options); } else { alert('error not location api'); } } function handle_errors(error) { switch(error.code) { case error.PERMISSION_DENIED: alert("user did not share geolocation data"); break; case error.POSITION_UNAVAILABLE: alert("could not detect current position"); break; case error.TIMEOUT: alert("retrieving position timed out"); break; default: alert("unknown error"); break; } } function initializeLocation(currLoc) { var currentLocation = currLoc; var mapLoc = new google.maps.LatLng(currentLocation["lat"], currentLocation["lng"]); var geocoder = new google.maps.Geocoder(); var mapOptions = { zoom: 17, center: mapLoc, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, navigationControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL, position: google.maps.ControlPosition.LEFT }, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_%(name)s"), mapOptions); var image = new google.maps.MarkerImage('/site_media/images/farallon.png', new google.maps.Size(16, 16), new google.maps.Point(0,0), new google.maps.Point(8,8)); var marker = new google.maps.Marker({ position: mapLoc, map: map, draggable: true, icon: image, }); var draw_circle = new google.maps.Circle({ center: marker.position, radius: geo_accuracy, strokeColor: "#1CA8F9", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#888888", fillOpacity: 0.35, map: map }); draw_circle.bindTo('center', marker, 'position'); $('#%(name)s_id')[0].value = marker.getPosition().lat() + "," + marker.getPosition().lng(); google.maps.event.addListener(marker, "dragend", function() { var point = marker.getPosition(); map.panTo(new google.maps.LatLng(point.lat(),point.lng())); if (geocoder) { geocoder.geocode( {'latLng': point}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) $('#%(name)s_id')[0].value = results[1].formatted_address; } else{ alert("Geocode was not successful for the following reason: " + status); } }); } }); } $(document).ready(function (){ getCurrentLocation(); }); $(document).unload(function () {GUnload()}); </script> ''' % dict(name=name, lat=lat, lng=lng, useDynamicLocation=self.dynamic_loc) html = self.inner_widget.render("%s" % name, None, dict(id='%s_id' % name)) html += """ <div id="loading" style="border: 1px solid #FFF;margin: 10px 0; padding: 5px 0 5px 0px;"></div> <div id=\"map_%s\" class=\"gmap\" style=\"width: %dpx; height: %dpx;\"> </div> """ % (name, self.map_width, self.map_height) return mark_safe(js + html)
class MapWidget(BaseContainerWidget): def __init__(self, data_widget, attrs=None): self.key_widget = TextInput() self.key_widget.is_localized = self.is_localized super(MapWidget, self).__init__(data_widget, attrs) def render(self, name, value, attrs=None): if value is not None and not isinstance(value, dict): raise TypeError("Value supplied for %s must be a dict." % name) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) fieldset_attr = {} # in Python 3.X dict.items() returns dynamic *view objects* value = list(value.items()) value.append(('', '')) for i, (key, widget_value) in enumerate(value): if id_: fieldset_attr = dict(final_attrs, id='fieldset_%s_%s' % (id_, i)) group = [] if not self.is_hidden: group.append( mark_safe('<fieldset %s>' % flatatt(fieldset_attr))) if id_: final_attrs = dict(final_attrs, id='%s_key_%s' % (id_, i)) group.append( self.key_widget.render(name + '_key_%s' % i, key, final_attrs)) if id_: final_attrs = dict(final_attrs, id='%s_value_%s' % (id_, i)) group.append( self.data_widget.render(name + '_value_%s' % i, widget_value, final_attrs)) if not self.is_hidden: group.append(mark_safe('</fieldset>')) output.append(mark_safe(''.join(group))) return mark_safe(self.format_output(output)) def value_from_datadict(self, data, files, name): i = 0 ret = {} while (name + '_key_%s' % i) in data: key = self.key_widget.value_from_datadict(data, files, name + '_key_%s' % i) value = self.data_widget.value_from_datadict( data, files, name + '_value_%s' % i) if key not in EMPTY_VALUES: ret.update(((key, value), )) i = i + 1 return ret def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = super(MapWidget, self)._get_media() media = media + self.key_widget.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super(MapWidget, self).__deepcopy__(memo) obj.key_widget = copy.deepcopy(self.key_widget) return obj
def render(self, name, value, attrs=None): attrs = self._must_have_id(attrs) return TextInput.render(self, name, value, attrs) + self.render_jquery_autocomplete(attrs)