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 __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 __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 __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'))
class ServicioEmpresaFilter(django_filters.FilterSet): id = django_filters.NumberFilter(field_name='id', lookup_expr='iexact', widget=NumberInput(attrs={'min': 1})) estado = django_filters.ChoiceFilter(choices=ESTADO_SERVICIO, field_name="estado", label="Estado") plaga = django_filters.ModelChoiceFilter( queryset=Plaga.objects.all(), field_name="solicitudServicio__plaga", label="Plaga") fecha = DateFilter(field_name="solicitudServicio__fecha", lookup_expr="iexact", label="Fecha", widget=TextInput(attrs={'placeholder': 'dd/mm/yyyy'})) class Meta: model = Servicio fields = ["id"] exclude = ["id"]
class ArticleAdminModelForm(ModelForm): body = CharField(widget=MarkdownWidget()) headline = CharField(label='Título', widget=TextInput(attrs={'style': 'width:600px'})) tags = TagField(widget=TagAutocompleteTagIt(max_tags=False), required=False) def clean_tags(self): """ This is a hack to bypass the bug that: 1 tag with spaces is considered as many tags by the lib. This doesn't ocurr with 2 tags or more. With double quotes, the tag with spaces is correctly interpreted. """ tags = self.cleaned_data.get('tags') if tags and ',' not in tags: # there is just 1 tag tags = tags.strip('"') tags = '"' + tags + '"' return tags class Meta: model = Article
class RoomUserAddForm(forms.Form): username = forms.CharField( widget=TextInput(attrs={ 'id': 'username', 'class': 'form-control', 'placeholder': _('Enter username') }), label=_('User name'), ) def clean_username(self): try: username = self.cleaned_data["username"] except KeyError: raise forms.ValidationError(_('You did not fill the field "User name"!')) try: User._default_manager.get(username=username) return username except User.DoesNotExist: raise forms.ValidationError(_("A user with the username %s does not exist!") % username)
class ElectronicsFilter(CommonFilter): title = django_filters.CharFilter(lookup_expr='icontains', label='Title', widget=TextInput(attrs={'placeholder': 'search...'})) class Meta: model = Electronics fields = ( 'title', 'desc', 'year', 'sell_price', 'rent_hour', 'rent_day', 'rent_week', 'rent_month', )
class Meta: model = Problem fields = [ 'title', 'short_name', 'pdf', 'time_limit', 'memory_limit', 'point', 'ballon', 'error', 'is_public' ] help_texts = { 'title': "* Enter title of problem", 'short_name': "* Enter short name of problem it must be less than 11 characters", 'pdf': "* Choose problem pdf", 'time_limit': "*Enter time limit of the problem in second", 'memory_limit': "Enter memory limit of the problem in megabytes", 'point': "*Enter point for the problem", 'ballon': "choose ballon color for the problem", } widgets = { 'pdf': forms.FileInput, 'ballon': TextInput(attrs={'type': 'color'}), }
class Meta: model = EDM fields = ('title', 'cover_image', 'cover_hype_link', 'cover_description', 'selection_articles', 'publish_time') widgets = { 'publish_time': DateTimeInput(attrs={'class': 'form-control'}), 'cover_description': Textarea(attrs={'class': 'form-control'}), 'selection_articles': SelectMultiple(attrs={'class': 'chosen-select'}), 'title': TextInput(attrs={'class': 'form-control'}), 'cover_hype_link': URLInput(attrs={'class': 'form-control'}) } labels = { 'title': _('title'), 'cover_image': _('cover image'), 'cover_hype_link': _('cover hype link'), 'cover_description': _('cover description'), 'selection_articles': _('selection articles'), 'publish_time': _('publish time') }
class Meta: model = Lote fields = '__all__' exclude = ['qtd_vendido', 'id_ingresso'] widgets = { 'nome': TextInput(attrs={'id': 'lote#nome'}), 'qtd_max': NumberInput(attrs={'id': 'lote#qtd_max'}), 'data_inicio_venda': DateInput(attrs={ 'class': 'datepicker', 'id': 'lote#data_inicio_venda' }), 'data_fim_venda': DateInput(attrs={ 'class': 'datepicker', 'id': 'lote#data_fim_venda' }), }
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" widget_attrs = { 'class': theme.form_element_html_class, 'type': 'email', 'placeholder': self.data.placeholder, } field_kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'widget': TextInput(attrs=widget_attrs), } if self.data.max_length not in (None, ''): field_kwargs['max_length'] = self.data.max_length return [(self.data.name, EmailField, field_kwargs)]
class UpdateDetailsCampaignAdmin(nested.NestedModelAdmin, SingletonModelAdmin): formfield_overrides = { models.TextField: { 'widget': Textarea(attrs = { 'rows': 5, 'cols': 200 })}, models.CharField: { 'widget': TextInput(attrs = { 'size': 200 })}, } inlines = [CampaignTagGroupInline, CampaignFieldInline, UrlParameterInline ] model = UpdateDetailsCampaign fields = ( ('fields_page_header', 'fields_page_footer', ), ('redirect_url'), ('nation_builder_url')) readonly_fields = ('nation_builder_url',) # URL for use in NationBuilder def nation_builder_url(self, campaign): parameters = [] for param in campaign.url_parameters.all().order_by('name'): parameters.append((param.name, param.nation_builder_value if param.nation_builder_value else '')) url = '<p>https://my.peoplesmomentum.com/members/update_details/1?%s</p>' % '&'.join('='.join(param) for param in parameters) return mark_safe(url)
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" widget_attrs = { 'class': theme.form_element_html_class, 'type': 'time', } field_kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, # 'input_formats': self.data.input_formats, 'required': self.data.required, 'widget': TextInput(attrs=widget_attrs), } # if self.data.input_formats: # kwargs['input_formats'] = self.data.input_formats return [(self.data.name, TimeField, field_kwargs)]
class SignupForm(UserCreationForm): username = forms.CharField(label="Имя пользователя", widget=TextInput(attrs={'id': 'username'})) email = forms.CharField(label="Электронная Почта", widget=EmailInput(attrs={'id': 'email'})) password1 = forms.CharField( label="Пароль", widget=PasswordInput(attrs={'id': 'password1'})) password2 = forms.CharField( label="Повторите Пароль", widget=PasswordInput(attrs={'id': 'password2'})) captcha = ReCaptchaField(widget=ReCaptchaWidget(), required=True) class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2', )
def get_form_field_instances(self, request=None): """ Get form field instances. """ widget_attrs = { 'class': theme.form_element_html_class, 'placeholder': self.data.placeholder, } kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'widget': TextInput(attrs=widget_attrs), } if self.data.max_length: kwargs['max_length'] = self.data.max_length return [(self.data.name, GenericIPAddressField, kwargs)]
class DocumentTextBlockInline(SortableInlineAdminMixin, admin.TabularInline): """The TextBlockInline class for the Document admin""" model = TextBlock autocomplete_fields = ["fragment"] readonly_fields = ("thumbnail", ) fields = ( "fragment", "multifragment", "side", "region", "order", "certain", "thumbnail", ) extra = 1 formfield_overrides = { CharField: { "widget": TextInput(attrs={"size": "10"}) } }
class ForumFilter(django_filters.FilterSet): forum = CharFilter(method='filter_by_all_name_fields', label='', widget=TextInput(attrs= { 'placeholder': 'Search forum', 'class': 'searchbox', })) #description = CharFilter(field_name='desc', lookup_expr='icontains') class Meta: model = Forum fields = '__all__' exclude = ['published', 'created_at', 'slug', 'owner', 'category', 'name', 'desc'] def filter_by_all_name_fields(self, queryset, name, value): return queryset.filter( Q(name__icontains=value) | Q(desc__icontains=value) )
class LoginAuthenticationForm(AuthenticationForm): """Form for authenticating a requested user. Authenticates a user against the provided username and password. User can use as username his email or his actual username. """ username = forms.CharField(required=True, max_length=50, widget=TextInput(attrs={ 'placeholder': 'username', 'class': 'form-control', 'required': 'true'})) password = forms.CharField(required=True, widget=PasswordInput(attrs={ 'placeholder': 'password', 'class': 'form-control', 'required': 'true'})) remember_me = forms.BooleanField( required=False, widget=forms.CheckboxInput()) def clean_remember_me(self): # if not self.cleaned_data.get('remember_me'): # self.request.session.set_expiry(0) # checked or not keep loged in self.request.session.set_expiry(0)
class SetupForm(forms.Form): username = forms.CharField(widget=TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Username', 'autofocus': 'true' }), help_text='You can chose a different username') email = forms.EmailField(widget=EmailInput(attrs={ 'class': 'form-control', 'placeholder': 'Email' })) password = forms.CharField(widget=PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Password' })) class Meta: model = Account fields = ['username', 'email', 'password']
class Meta: model = Sanciones fields = "__all__" widgets = { 'IdAlumno': HiddenInput(), 'Fecha': SelectDateWidget(years=(datetime.date.today().year, datetime.date.today().year - 1)), 'Fecha_fin': SelectDateWidget(years=(datetime.date.today().year, datetime.date.today().year - 1)), 'Sancion': TextInput(attrs={'size': '67'}), 'Comentario': Textarea(attrs={ 'cols': 80, 'rows': 15 }), #'Comentario': TinyMCE(), }
class FilterPending(Form): searchtext = CharField( label=_("SEARCH_TEXT"), required=False, widget=TextInput(attrs={ 'class': 'form-control', 'placeholder': _('SEARCH_TITLE_AND_TAGS') })) ordering = ChoiceField(choices=[ ('REWARD_HIGHEST', _('REWARD_HIGHEST')), ('REWARD_LOWEST', _('REWARD_LOWEST')), ('DEADLINE_NEAREST', _('DEADLINE_NEAREST')), ('DEADLINE_FARTHEST', _('DEADLINE_FARTHEST')), ('NEWEST_BOUNTY', _('NEWEST_BOUNTY')), ('OLDEST_BOUNTY', _('OLDEST_BOUNTY')), ], label=_("ORDERING"), initial="REWARD_HIGHEST", widget=Select(attrs={'class': 'form-control'}))
class SearchMinForm(forms.Form): q = forms.CharField( max_length=50, label=u'Ключевое слово, фраза', required=False, widget=TextInput(attrs={ 'placeholder': u'Ключевое слово, фраза', 'class': 'span11' })) category = forms.ModelMultipleChoiceField(queryset=Category.activs.all(), label=u'Раздел', required=False) type_search = forms.ChoiceField( choices=TYPE_SEARCH, widget=forms.RadioSelect(attrs={'required': True}), label=u'', required=True) def __init__(self, type_search=TYPE_SEARCH[0][0], *args, **kwargs): super(SearchMinForm, self).__init__(*args, **kwargs) self.fields['type_search'].initial = type_search
def __init__(self, *args, **kwargs): super(StoryEditionForm, self).__init__(*args, **kwargs) self.fields['as_a'].widget = TextInput() self.fields['as_a'].widget.attrs['autofocus'] = '' self.fields['as_a'].widget.attrs['class'] = 'form-control input-large' self.fields['color'].widget.attrs['colorpicker'] = 'true' self.fields['i_want_to'].widget.attrs['placeholder'] = _( "be able to input text here") self.fields['so_i_can'].widget.attrs['placeholder'] = _( "write user stories") self.fields['acceptances'].widget.attrs['placeholder'] = _( "- user story readable by human") self.fields['acceptances'].help_text = _( "Use markdown list format: line with '-' in front") if self.instance: self.initial['points'] = "" if self.instance.points == -1 \ else self.instance.points else: self.initial['points'] = self.initial.get('points', "") setup_bootstrap_fields(self)
class SignUpForm(UserCreationForm): username = forms.CharField( required=True, widget=TextInput(attrs={ 'placeholder': 'Username', 'autocomplete': 'off' })) email = forms.CharField(max_length=255, required=True, widget=forms.EmailInput(attrs={ 'placeholder': 'Email', 'autocomplete': 'off' })) password1 = forms.CharField(widget=PasswordInput( attrs={'placeholder': 'Password'})) password2 = forms.CharField(widget=PasswordInput( attrs={'placeholder': 'Confirm Password'})) class Meta: model = User fields = ('username', 'email', 'password1', 'password2')
class FullEmailOrPhoneForm(forms.Form): email_or_phone = forms.CharField( max_length=50, label="Email or phone number", required=True, widget=TextInput(attrs={'placeholder': 'Enter here'})) class Meta: model = User fields = ('email_or_phone', ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_email_or_phone(self): email_or_phone = self.cleaned_data['email_or_phone'] if email_or_phone == self.user.email or email_or_phone == self.user.phone: return email_or_phone else: raise ValidationError("User doesn't exist")
class Meta: model = Viagem fields = ('status', 'localPartida', 'localChegada', 'caixa', 'equipamento', 'nomeTransportador', 'contato', 'obs', 'dataInicio', 'dataFim') widgets = { 'contato': TextInput(attrs={'class': 'phone'}), 'obs': Textarea( attrs={ 'rows': '5', 'onkeyup': "mostrarResultado(this.value,500,'spcontando');contarCaracteres(this.value,500,'sprestante')" }), 'dataInicio': DateTimeWidget(usel10n=True, attrs={'data-readonly': 'false'}), 'dataFim': DateTimeWidget(usel10n=True, attrs={'data-readonly': 'false'}) }
class FeriadoFormCreateUpdate(forms.ModelForm): data_feriado = forms.DateField( validators=[validate_weekend], label='DATA', error_messages={ 'required': 'Informe a data!', 'unique': 'Já existe um FERIADO (ou dia não útil) cadastrado com esta DATA!' }, widget=TextInput(attrs={'type': 'date'})) #},widget=DateInput()) #label_suffix='' funciona no create mas não funciona no update descricao = forms.CharField(label='DESCRIÇÃO/MOTIVO', widget=forms.Textarea(attrs={ 'rows': '3', 'columns': '10' })) class Meta: model = Feriado exclude = ['id']
class LeaveForm(forms.ModelForm): dateStart = forms.CharField(label='Departure Date', widget=forms.TextInput(attrs={'class': 'datepicker mask'})) timeStart = forms.CharField(label='Departure Time', widget=forms.TextInput(attrs={'class': 'timepicker mask'})) dateEnd = forms.CharField(label='Arrival Date', widget=forms.TextInput(attrs={'class': 'datepicker mask'})) timeEnd = forms.CharField(label='Arrival Time', widget=forms.TextInput(attrs={'class': 'timepicker mask'})) phone_number = forms.CharField(label='Contact No. during leave', widget=TextInput(attrs={'type':'number'})) def clean(self): cleaned_data = super(LeaveForm, self).clean() dateStart = datetime.strptime(cleaned_data['dateStart'], '%d %B, %Y').date() dateEnd = datetime.strptime(cleaned_data['dateEnd'], '%d %B, %Y').date() timeStart = datetime.strptime(cleaned_data['timeStart'], '%H:%M').time() date_time_start = datetime.combine(dateStart, timeStart) if (len(cleaned_data['phone_number']) > 10): self.add_error('phone_number', "Phone No. can't be longer than 15 numbers") if (dateStart > dateEnd): self.add_error('dateEnd', "Arrival cannot be before Departure") if (datetime.now() >= date_time_start): self.add_error('dateStart', "Departure cannot be before the present date and time") if((date_time_start-datetime.now()).days>30): self.add_error('dateStart', "Can apply for leaves within a month only.") if (date_time_start - datetime.now()) <= timedelta(hours=12): self.add_error('dateStart', "Cannot apply for leave one day before departure. Contact warden for immediate leave approval") if (dateStart - dateEnd).days == 0: self.add_error('dateStart', "Start date and end date cannot be the same. Apply for a day pass instead") return cleaned_data class Meta: model = Leave exclude = ['dateTimeStart', 'dateTimeEnd', 'student', 'approvedBy', 'approved', 'disapproved', 'inprocess', 'comment', 'corrPhone'] widgets = { 'reason': forms.Textarea(attrs={'class': 'materialize-textarea validate'}), 'corrAddress': forms.Textarea(attrs={'class': 'materialize-textarea validate'}), } labels = { 'consent': _('Parent Consent Type'), 'corrAddress': _('Address for Correspondence during Leave'), 'corrPhone': _('Contact No. during Leave'), }
class ProfileForm(SignupForm): # ProfileForm GENDER_CHOICES = (('m', 'Male'), ('f', 'Female')) username = None password = None confirm_password = None national_id = forms.CharField(required=True, widget=TextInput()) dob = forms.DateField(required=True) gender = forms.ChoiceField(required=True, choices=GENDER_CHOICES) image = forms.ImageField(required=False) country = forms.CharField(required=True) city = forms.CharField(required=True) district = forms.CharField(required=True, widget=TextInput()) area = forms.CharField(required=True, widget=TextInput()) street_no = forms.IntegerField(required=True, widget=TextInput()) phone_no1 = forms.CharField(required=True, widget=TextInput()) phone_no2 = forms.CharField(required=False, widget=TextInput())
def __init__(self, user_type, users_turn, ccyys, routed_to_dean, approved_by_reg, *args, **kwargs): super(MajorForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-majorForm' self.helper.form_tag = False self.helper.layout = Layout(InlineField('school', 'major_code', 'minor', 'catalog_begin', 'catalog_end')) # gets the list of valid school choices for the given CCYYS schools = School.objects.filter(begin_ccyys__lte=ccyys).filter( end_ccyys__gte=ccyys) # If we've already gone through once with the form, (even if it's # via ajax) we will have some data. If we have a school picked, # then we can figure out the valid major choices. If no school is # picked, use the majors from the student's current college. if 'school' in self.data: majors = Major.objects.filter(school=self.data['school']).filter(begin_ccyys__lte=ccyys).filter(end_ccyys__gte=ccyys) else: majors = Major.objects.filter(school=self.instance.school).filter(begin_ccyys__lte=ccyys).filter(end_ccyys__gte=ccyys) # choice fields have to be in format [(code, display),] major_choices = [(major.code, str(major.code) + " " + major.long_desc) for major in majors] self.fields['major_code'] = forms.ChoiceField(choices=major_choices, required=False) self.fields['school'].queryset = schools self.fields['school'].label = 'College' self.fields['school'].requires = True self.fields['major_code'].label = 'Major' self.fields['minor'].required = False self.fields['catalog_begin'].required = False self.fields['catalog_end'].required = False if not users_turn or user_type == 'D' or (user_type == 'A' and routed_to_dean) or approved_by_reg: self.fields['school'].widget = HiddenInput() self.fields['major_code'].widget = HiddenInput() self.fields['catalog_begin'].widget = TextInput(attrs={'readonly': 'readonly'}) self.fields['minor'].widget.attrs['readonly'] = 'readonly'
class Meta: model = Service fields = [ 'facility', 'facility_type', 'service_offered', 'contact', 'region', 'district', 'location' ] widgets = { 'facility': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter facility' }), 'facility_type': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter facility type' }), 'service_offered': Textarea( attrs={ 'class': 'form-control no-resize', 'placeholder': 'Enter services offered', 'rows': 40, 'id': 'summernote', 'style': 'display: none;' }), 'contact': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter contact' }), 'region': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter region' }), 'district': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter district' }), 'location': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'enter location' }), }
class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'date_of_birth', 'country', 'state', 'profile_picture', 'intro', 'text'] exclude = ['password'] help_texts = { 'username': None, 'email': None, } labels = { 'state': 'State/Province', 'first_name': 'First Name', 'last_name': 'Last Name', 'profile_picture': 'Profile Picture', 'intro': 'Introduction (max 100 characters)', 'text': 'Profile Text (max 1000 characters)', 'date_of_birth': 'Date of Birth', } widgets = { 'date_of_birth': TextInput(attrs={'type': 'date'}), 'profile_picture': ThumbnailWidget(), }
def __init__(self, attrs={}, date_format=None, time_format=None): if 'date_class' in attrs: date_class = attrs['date_class'] del attrs['date_class'] else: date_class = 'datepicker' if 'time_class' in attrs: time_class = attrs['time_class'] del attrs['time_class'] else: time_class = 'timepicker' time_attrs = attrs.copy() time_attrs['class'] = time_class date_attrs = attrs.copy() date_attrs['class'] = date_class widgets = (DateInput(attrs=date_attrs, format=date_format), TextInput(attrs=time_attrs)) super(SplitDateTimeWidget, self).__init__(widgets, attrs)
def __init__(self, lookup_name, attrs=None): TextInput.__init__(self, attrs) AutocompleteWidget.__init__(self, lookup_name, attrs)
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)
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 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 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)
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 __init__(self, url=None, filter_fields=None, extra_fields=None, *largs, **kwargs): ''' Autocomplete ''' TextInput.__init__(self, *largs, **kwargs) self.filter_fields = filter_fields