class SurveySearchForm(forms.Form): search_text = forms.CharField(required=False) def get_queryset(self): object_list = Survey.objects.all() return object_list
class EnrolleesAdminForm(forms.ModelForm): description = forms.CharField(label="Описание", widget=CKEditorUploadingWidget()) class Meta: model = ForEnrollee fields = '__all__'
class SearchForm(forms.Form): postcode = forms.CharField(max_length=50, required=False, help_text="Enter a Post code to search from") use_current_location = forms.BooleanField(initial=False, required=False) search_radius = forms.IntegerField(min_value=0, max_value=200, help_text="Search distance (Miles)") maximum_length = forms.IntegerField( required=False, min_value=0, max_value=250, help_text="Maximum walk length (Miles)", ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for attribute in Attribute.objects.all(): self.fields[attribute.attribute] = forms.BooleanField( initial=False, required=False) def clean(self): if (not self.cleaned_data["postcode"] and not self.cleaned_data["use_current_location"]): raise forms.ValidationError( "You must enter a postcode or location or use your current location" )
def __init__(self, *args, **kwargs): categorias = GruposCategorias.objects.get( grupo='Infraestructura').idGruposCategorias.values_list( 'categoria') CHOICE_CATEGORIAS = [] # diccionario del menu for choice in categorias: CHOICE_CATEGORIAS.append((choice[0], choice[0])) super(FormInfraestructura, self).__init__(*args, **kwargs) self.fields['nombre'].widget.attrs.update({'class': 'form-control'}) self.fields['id_inst'].widget.attrs.update({'class': 'form-control'}) self.fields['descripcion'].widget.attrs.update({ 'class': 'form-control', 'row': 3 }) self.fields['categoria'] = forms.CharField( label='Categoria', required=False, help_text='Seleccione la categoria', widget=forms.Select(attrs={ 'class': "form-control", 'placeholder': 'Categoria', 'rows': 1 }, choices=CHOICE_CATEGORIAS)) #self.fields['geom']=forms.GeometryField(srid='4326',widget=forms.Textarea) #self.fields['geometria'].widget.attrs.update({'class': 'form-control-file'}) #self.fields['geom'].widget.attrs.update({'template_name':'cynr_app/geomFormItem.html','class': 'form-control'}) self.fields['ficha_tec'].widget.attrs.update( {'class': 'form-control-file'})
class RasterQueryForm(QuerySetForm): """Validates format options for raster data.""" bbox = fields.BoundingBoxField(required=False) format = forms.CharField(required=False) g = fields.OGRGeometryField(required=False) upload = fields.GeometryFileField(required=False) periods = forms.IntegerField(required=False) stat = forms.ChoiceField(choices=[ (choice, ) * 2 for choice in 'max', 'mean', 'median', 'min', 'std', 'var' ], required=False) def clean(self): """Return cleaned fields as a dict, determine which geom takes precedence. """ data = super(RasterQueryForm, self).clean() data['g'] = data.pop('upload') or data.pop('bbox') or data.get('g') return data def select(self): format, geom, stat, periods = map(self.cleaned_data.get, ('format', 'g', 'stat', 'periods')) if format in ('csv', 'json'): if not geom: return qs = self.queryset.summarize(geom, stat) else: qs = self.queryset.warp(format, geom=geom) if periods: qs = qs.aggregate_periods(periods) self.queryset = qs
class TrackForm(forms.Form): tracks = forms.CharField( label=_('Routes'), widget=forms.HiddenInput(attrs={'bikeanjo-geojson': 'lines'}), required=False) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(TrackForm, self).__init__(*args, **kwargs) def clean_tracks(self): if not self.cleaned_data.get('tracks'): return [] try: lines = json.loads(self.cleaned_data.get('tracks')) tracks = [] for line in lines: _id = line.get('properties').get('id') if _id: track = models.Track.objects.get(id=_id) else: track = models.Track() track.track = LineString([c for c in line.get('coordinates')]) track.start = line.get('properties').get('start') track.end = line.get('properties').get('end') tracks.append(track) return tracks except ValueError, e: raise forms.ValidationError(e.message)
def __init__(self, *args, **kwargs): categorias = GruposCategorias.objects.get( grupo='Documentos Institucionales').idGruposCategorias.values_list( 'categoria') CHOICE_CATEGORIAS = [] # diccionario del menu for choice in categorias: CHOICE_CATEGORIAS.append((choice[0], choice[0])) super(FormDocInstitucionales, self).__init__(*args, **kwargs) self.fields['nombre'].widget.attrs.update({'class': 'form-control'}) self.fields['id_inst'].widget.attrs.update({'class': 'form-control'}) self.fields['presentacion'].widget.attrs.update({ 'class': 'form-control', 'row': 3 }) self.fields['categoria'] = forms.CharField( label='Categoria', required=False, help_text='Seleccione la categoria', widget=forms.Select(attrs={ 'class': "form-control", 'placeholder': 'Categoria', 'rows': 1 }, choices=CHOICE_CATEGORIAS)) self.fields['link_doc'].widget.attrs.update({'class': 'form-control'}) self.fields['arch_doc'].widget.attrs.update( {'class': 'form-control-file'}) self.fields['alc_geografico'].widget.attrs.update( {'class': 'form-control'})
class GeometryQueryForm(QuerySetForm): """A form providing GeoQuerySet method arguments.""" format = forms.CharField(required=False) precision = forms.IntegerField(required=False) # Tolerance value for geometry simplification simplify = forms.FloatField(required=False) srs = fields.SpatialReferenceField(required=False) def select(self): kwargs = {} data = self.cleaned_data if data['precision'] is not None: kwargs.update(precision=data['precision']) tolerance, srs, format = map(data.get, ('simplify', 'srs', 'format')) srid = getattr(srs, 'srid', None) try: has_format = self.queryset.has_format(format) except AttributeError: # Handle default GeoQuerySet. try: self.queryset = getattr(self.queryset, format)(**kwargs) except AttributeError: pass else: if has_format: kwargs.update(format=format) self.queryset = self.queryset.simplify(tolerance, srid, **kwargs)
class MovieAdminForm(forms.ModelForm): description = forms.CharField(label='Tavfsifi', widget=CKEditorUploadingWidget()) class Meta: model = Movie fields = '__all__'
class ConfirmedCaseForm(forms.Form): estimated_date_contracted = forms.DateField( input_formats=['%Y-%m-%d'], widget=XDSoftDatePickerInput(), label='Estimated Date Contracted') date_first_symptoms = forms.DateField(input_formats=['%Y-%m-%d'], widget=XDSoftDatePickerInput(), label='Date of First Symptoms') date_confirmed = forms.DateField(input_formats=['%Y-%m-%d'], widget=XDSoftDatePickerInput(), label='Date Confirmed') additional_info = forms.CharField(widget=BootstrapTextArea(), label='Additional Information', max_length=40000, required=False) age_range = forms.ChoiceField(widget=BootstrapSelect(choices=age_ranges), choices=age_ranges) gender = forms.ChoiceField(widget=BootstrapSelect(choices=genders), choices=genders) diseases = MultiBinaryField( widget=BootstrapMultiBinaryRadio(options=diseases), choices=diseases)
class SignupAgreementForm(forms.ModelForm): check1 = forms.BooleanField() check2 = forms.BooleanField() check3 = forms.BooleanField() check4 = forms.BooleanField() check5 = forms.BooleanField() check6 = forms.BooleanField() accepted_agreement = forms.BooleanField() message = forms.CharField() def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(SignupAgreementForm, self).__init__(*args, **kwargs) self.fields['message'].required = (self.user.role == 'requester') def clean(self): cleaned_data = super(SignupAgreementForm, self).clean() msg = 'Você deve aceitar os termos para usar o site' for field, value in cleaned_data.items(): if field != 'message' and not value: self.add_error(field, msg) class Meta: model = models.User fields = ('accepted_agreement', )
class BikeanjoAcceptRequestForm(forms.ModelForm): reason = forms.CharField(label=_('Reason'), widget=forms.HiddenInput, required=False) def save(self, **kwargs): data = self.cleaned_data req = self.instance if req.status == 'new': if req.bikeanjo: match, created = req.match_set.get_or_create( bikeanjo_id=req.bikeanjo.id) match.rejected_date = now() match.reason = data.get('reason') match.save() req.bikeanjo = None super(BikeanjoAcceptRequestForm, self).save(self, **kwargs) if req.status == 'open': enqueue_15days_notification_for_open_requests(self.instance) notify_requester_about_found_bikeanjo(self.instance) return self.instance class Meta: model = models.HelpRequest fields = ('status', )
class GeometryQueryForm(QuerySetForm): """A form providing GeoQuerySet method arguments.""" format = forms.CharField(required=False) precision = forms.IntegerField(required=False, initial=4) # Tolerance value for geometry simplification simplify = forms.FloatField(required=False) srs = fields.SpatialReferenceField(required=False) def clean_precision(self): # Unfortunately initial values are not used as default values. return (self.cleaned_data['precision'] or self.fields['precision'].initial) def select(self): data = self.cleaned_data kwargs = {'precision': data['precision']} tolerance, srs, format = map(data.get, ('simplify', 'srs', 'format')) srid = getattr(srs, 'srid', None) try: has_format = self.queryset.has_format(format) except AttributeError: # Handle default GeoQuerySet. try: self.queryset = getattr(self.queryset, format)(**kwargs) except AttributeError: pass else: if has_format: kwargs.update(format=format) self.queryset = self.queryset.simplify(tolerance, srid, **kwargs)
class DepartmentsAdminForm(forms.ModelForm): description = forms.CharField(label="Описание", widget=CKEditorUploadingWidget()) class Meta: model = Departments fields = '__all__'
class VectorTileForm(TileForm): clip = forms.BooleanField(required=False, initial=True) format = forms.CharField(required=False) def select(self): data = self.cleaned_data self.queryset = self.queryset.tile(data['bbox'], data['z'], data['format'], data['clip'])
class PasswordResetForm(forms.Form): old_password = forms.CharField(label=_('Password'), widget=forms.PasswordInput, required=False) password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput) password2 = forms.CharField(label=_('Password (again)'), widget=forms.PasswordInput) def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance') super(PasswordResetForm, self).__init__(*args, **kwargs) def clean_old_password(self): old_password = self.cleaned_data.get('old_password') if not self.instance.has_usable_password() or\ self.instance.check_password(old_password): return old_password raise forms.ValidationError('A senha antiga está incorreta.') def clean_password1(self): pass1 = self.cleaned_data.get('password1') if self.instance.has_usable_password() and\ self.instance.check_password(pass1): raise forms.ValidationError('A nova senha é igual a antiga') return pass1 def clean_password2(self): pass1 = self.cleaned_data.get('password1') pass2 = self.cleaned_data.get('password2') if pass1 == pass2: return pass1 raise forms.ValidationError('As senhas devem ser iguais') def save(self, **kwargs): password = self.cleaned_data.get('password2') self.instance.set_password(password) self.instance.save() return self.instance
class GeoNamesMatchingLogMatchForm(ModelForm): object_id = forms.CharField(widget=forms.TextInput( attrs={'readonly': 'readonly'})) class Meta: model = GeoNamesMatchingLogMatch exclude = ('display_for_users', 'number_of_alternatives', 'content_type')
class MovieAdminForm(forms.ModelForm): '''Форма с виджетом ckeditor''' description = forms.CharField(label='Описание', widget=CKEditorUploadingWidget()) class Meta: model = Movie fields = '__all__'
class PointsForm(forms.Form): points = forms.CharField( label=_('Points'), widget=forms.HiddenInput(attrs={'bikeanjo-geojson': 'points'}), required=False) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PointsForm, self).__init__(*args, **kwargs) self['points'].field.initial = self.load_points() def clean_points(self): points = [] if not self.cleaned_data.get('points'): return points try: json_points = json.loads(self.cleaned_data.get('points')) if not json_points: return points for p in json_points: _id = p.get('properties').get('id') if _id: point = models.Point.objects.get(id=_id) else: point = models.Point() point.coords = Point(p.get('coordinates')) point.address = p.get('properties').get('address') points.append(point) return points except ValueError: pass return points def save(self): points = self.cleaned_data['points'] existent = [point.id for point in points if point.id] self.user.point_set.exclude(id__in=existent).delete() for point in points: point.user = self.user point.save() return self.cleaned_data['points'] def load_points(self): if self.errors: return '[]' points = models.Point.objects.filter(user=self.user) return '[%s]' % ','.join([p.json() for p in points])
class LabNetworkForm(FormCleanMixin): operational_since = forms.ChoiceField( choices=hospital_operational_since_choices, required=False) about = forms.CharField(widget=forms.Textarea, required=False) class Meta: model = LabNetwork exclude = () widgets = { 'matrix_state': autocomplete.ModelSelect2(url='matrix-state-autocomplete'), 'matrix_city': autocomplete.ModelSelect2(url='matrix-city-autocomplete', forward=['matrix_state']) } def validate_qc(self): qc_required = { 'name': 'req', 'operational_since': 'req', 'about': 'req', 'network_size': 'req', 'building': 'req', 'locality': 'req', 'matrix_city': 'req', 'matrix_state': 'req', 'country': 'req', 'pin_code': 'req', 'labnetworkmanager': 'count', 'labnetworkhelpline': 'count', 'labnetworkemail': 'count' } # if self.instance.is_billing_enabled: # qc_required.update({ # 'lab_documents': 'count' # }) for key, value in qc_required.items(): if value == 'req' and not self.cleaned_data[key]: raise forms.ValidationError(key + " is required for Quality Check") if self.data.get(key + '_set-TOTAL_FORMS') and value == 'count' and int( self.data[key + '_set-TOTAL_FORMS']) <= 0: raise forms.ValidationError("Atleast one entry of " + key + " is required for Quality Check") if self.data.get(key + '-TOTAL_FORMS') and value == 'count' and int( self.data.get(key + '-TOTAL_FORMS')) <= 0: raise forms.ValidationError("Atleast one entry of " + key + " is required for Quality Check") def clean_operational_since(self): data = self.cleaned_data['operational_since'] if data == '': return None return data
class GeoNamesMatchingLogMatchedPlacesFormUser(autocomplete_light.ModelForm): united_geoname = autocomplete_light.ModelChoiceField( 'UnitedGeoNameAutocomplete') remark = forms.CharField(widget=forms.TextInput(attrs={'size': '30'}), required=False) class Meta: model = GeoNamesMatchingLogMatchedPlaces exclude = ('matchinglogmatch', )
class BaseMapForm(forms.ModelForm): title = forms.CharField(label="Titre", required=True) class Meta: model = BaseMap fields = [ 'title', ]
class HelpRequestCompleteForm(forms.ModelForm): help_with = forms.IntegerField() geo_json = forms.CharField(widget=forms.HiddenInput(), required=True) def save(self): self.instance.track = self.save_track() super(HelpRequestCompleteForm, self).save() self.save_points() self.instance.assign_bikeanjo() if self.instance.bikeanjo: notify_bikeanjo_about_new_request(self.instance) return self.instance def save_points(self): geo_json = self.cleaned_data.get('geo_json') points = [] for p in geo_json.get('points', []): point = models.Point() point.helprequest = self.instance point.user = self.instance.requester point.coords = Point(p.get('coordinates')) point.address = p.get('properties').get('address') points.append(point) self.instance.point_set.bulk_create(points) return points def save_track(self): geo_json = self.cleaned_data.get('geo_json') line = geo_json.get('track') if not line: return track = models.Track() track.user = self.instance.requester track.track = LineString([c for c in line.get('coordinates')]) track.start = line.get('properties').get('start') track.end = line.get('properties').get('end') track.save() return track def clean_geo_json(self): if type(self.data['geo_json']) in (list, dict): return self.data['geo_json'] return self.cleaned_data['geo_json'] class Meta: model = models.HelpRequest fields = ( 'help_with', 'message', )
class SignupRequesterForm(forms.ModelForm): gender = forms.CharField(label=_('Gender')) birthday = forms.DateField(label=_('Date of birth'), input_formats=["%d/%m/%Y"]) ride_experience = forms.ChoiceField(choices=models.REQUESTER_EXPERIENCE) class Meta: model = models.User fields = ('gender', 'birthday', 'ride_experience')
class RespuestaSinoForm(forms.Form): """! Clase que permite crear el formulario para las respuestas de tipo SiNo @author Manuel Zambrano @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 29-08-2018 @version 1.0.0 """ respuesta = forms.BooleanField(label='Respuesta', widget=forms.Select(choices=((True, 'Si'), (False, 'No'))), required=False) justificacion = forms.CharField( label='Respuesta', widget=forms.Textarea(), required=False, min_length=128, ) def __init__(self, *arg, **kwargs): """! Funcion que muestra el init del formulario @author Manuel Zambrano @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 29-08-2018 @version 1.0.0 """ super(RespuestaSinoForm, self).__init__(*arg, **kwargs) self.fields['justificacion'].widget.attrs.update({ 'placeholder': 'Justificacion', 'style': 'width:370px;height:191px;' }) def clean(self): """! Funcion que sobreescribe el metodo clean() de la clase, validación para el campo de justificacion @author Manuel Zambrano @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 29-08-2018 @version 1.0.0 """ cleaned_data = super(RespuestaSinoForm, self).clean() clean_respuesta = cleaned_data.get('respuesta') clean_justificacion = cleaned_data.get('justificacion') if not clean_respuesta: if not clean_justificacion: raise forms.ValidationError( "Verifique el campo de justificacion", code="justificacion_error")
class ProfileSearchForm(forms.Form): search_text = forms.CharField(required=False) def get_queryset(self): object_list = UserProfile.objects.all() if self.is_valid(): if self.cleaned_data['search_text']: object_list = object_list.filter(name__icontains=self.cleaned_data['search_text']) return object_list
class AddPosgresViewAdminForm(forms.Form): name = forms.CharField(label="Nom", required=True, validators=[alphanumeric]) status = forms.MultipleChoiceField(label="Statut", choices=tuple( x for x in Feature.STATUS_CHOICES), widget=forms.CheckboxSelectMultiple, required=False)
class Normal2BScanVectorizedModelForm(forms.ModelForm): name = forms.CharField( label='Update the NAME of Normal2BScanVectorized', max_length=254, required=False, widget=forms.TextInput(attrs={'class': 'form-control mr-sm-1'})) class Meta: model = Normal2BScanVectorized fields = ['name']
class RasterTileForm(TileForm): band = forms.IntegerField(required=False, initial=1) size = forms.IntegerField(required=False, initial=256) limits = fields.CommaSepFloatField(required=False) style = forms.CharField(required=False) def clean_band(self): return self.cleaned_data['band'] or self.fields['band'].initial def clean_style(self): # Mapnik requires string, not unicode, for style names. return str(self.cleaned_data['style'])
class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the name of the food") url = forms.ChoiceField(choices=FOOD_CHOICES, help_text="Please select the type of food it is") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: # Provide an association between the ModelForm and a model model = Page # What fields do we want to include in our form? # This way we don't need every field in the model present. # Some fields may allow NULL values, so we may not want to include them… # Here, we are hiding the foreign key. fields = ('title', 'url', 'views')