class CommentForm(forms.ModelForm): comment = forms.CharField(required=True, widget=forms.Textarea()) title = forms.CharField(label="Titre de la pièce jointe", required=False) attachment_file = forms.FileField(label="Fichier joint", required=False) info = forms.CharField( label="Information additionnelle au fichier joint", required=False, widget=forms.Textarea()) class Meta: model = Comment fields = ( 'comment', 'title', 'attachment_file', 'info', ) def clean(self): cleaned_data = super().clean() up_file = cleaned_data.get("attachment_file") title = cleaned_data.get("title") if up_file and not title: raise forms.ValidationError( "Veuillez donner un titre à votre pièce jointe. " ) return cleaned_data
class RespuestaAbiertaForm(forms.Form): """! Clase que permite crear el formulario para las respuestas de tipo Abierta @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.CharField(label='Respuesta', widget=forms.Textarea(), 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(RespuestaAbiertaForm, self).__init__(*arg, **kwargs) self.fields['respuesta'].widget.attrs.update({ 'placeholder': 'Respuesta', 'style': 'width:370px;height:191px;' })
class NewProjectionPhotoForm(forms.Form): # projection type front_view_photo = "FRT" side_first_view_photo = "SD1" side_second_view_photo = "SD2" back_view_photo = "BCK" projection_view_type = forms.ChoiceField(label=_('Выберите вид к которому относится фото'), widget = forms.Select(attrs = {'class': 'form-control'}), choices = ( (front_view_photo, _('Передний вид')), (side_first_view_photo, _('Боковой вид №1')), (side_second_view_photo, _('Боковой вид №2')), (back_view_photo, _('Задний вид')), ) ) # фото проекции projection_view_photo = forms.ImageField(label=_("Выберите изображение"), widget = forms.ClearableFileInput(attrs = {'class': 'form-control', 'type':'file'})) projection_view_description = forms.CharField(label=_('Описание'), max_length=100, required=False, widget = forms.Textarea(attrs = {'class': 'form-control', 'rows': "5" } ) )
class Meta: model = CzarApplication exclude = ['application_reviewed', 'czar_granted'] labels = { 'name_first': 'First Name', 'name_last': 'Last Name', 'municipality': 'Location', 'description': 'About You', 'twitter': 'Twitter', 'url': 'URL' } widgets = { 'description': forms.Textarea( attrs={ 'rows': 3, 'placeholder': 'Why you are a good fit for this role' }), 'municipality': forms.TextInput(attrs={'placeholder': 'Municipality/City/Region'}), 'twitter': forms.TextInput(attrs={'placeholder': 'Twitter (optional)'}), 'url': forms.TextInput(attrs={'placeholder': 'URL (optional)'}) }
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 UserMapForm(forms.Form): name = forms.CharField(max_length=100) description = forms.CharField( max_length=5000, widget=forms.Textarea(attrs={ 'rows': 30, 'cols': 20, 'style': 'height: 5em;' })) aoi = gisforms.gis.PolygonField(widget=OsmPolygonWidget)
def __init__(self, *args, **kwargs): extra = kwargs.pop('extra', None) feature = kwargs.pop('feature', None) super().__init__(*args, **kwargs) for custom_field in extra.order_by('position'): if custom_field.field_type == 'boolean': self.fields[custom_field.name] = forms.BooleanField( label=custom_field.label, initial=False, required=False, ) if custom_field.field_type == 'char': self.fields[custom_field.name] = forms.CharField( label=custom_field.label, max_length=256, required=False) if custom_field.field_type == 'date': self.fields[custom_field.name] = forms.DateField( label=custom_field.label, required=False, ) if custom_field.field_type == 'integer': self.fields[custom_field.name] = forms.IntegerField( label=custom_field.label, required=False) if custom_field.field_type == 'decimal': self.fields[custom_field.name] = forms.DecimalField( label=custom_field.label, required=False, widget=forms.TextInput(attrs={'localization': False})) if custom_field.field_type == 'text': self.fields[custom_field.name] = forms.CharField( label=custom_field.label, required=False, widget=forms.Textarea()) if custom_field.field_type == 'list' and custom_field.options: self.fields[custom_field.name] = forms.ChoiceField( label=custom_field.label, choices=[(str(xx), str(xx)) for xx in custom_field.options], required=False) self.fields[custom_field.name].widget.attrs.update( {'field_type': custom_field.field_type}) if feature and isinstance(feature.feature_data, dict): for custom_field in extra: self.fields[ custom_field.name].initial = feature.feature_data.get( custom_field.name)
class AddMessageToEventMarkForm(forms.Form): eventmarkid = forms.CharField(widget=forms.HiddenInput()) message = forms.CharField(label=_('Message'), widget=forms.Textarea(attrs={ 'cols': '', 'rows': '' }), required=True) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super(AddMessageToEventMarkForm, self).__init__(*args, **kwargs)
class AddEventMarkForm(forms.Form): point = forms.PointField(widget=TDOSMWidget(), label='') message = forms.CharField(label=_('Message'), widget=forms.Textarea(attrs={ 'cols': '', 'rows': '' }), required=True) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super(AddEventMarkForm, self).__init__(*args, **kwargs)
class Meta: model = Event exclude = ['venue', 'host', 'slug'] labels = { 'start': 'Start Time', 'end': 'End Time', 'recurrences': 'Date / Recurring Schedule', 'url': 'URL' } widgets = { 'description': forms.Textarea(attrs={'rows': 3}), 'start': forms.TimeInput(attrs={'type': 'time'}), 'end': forms.TimeInput(attrs={'type': 'time'}) }
class CompanyUpdate(LoginRequiredMixin, UpdateView): login_url = '/login/' redirect_field_name = 'redirect_to' permission_denied_message = "You don't have an acess to edit companies" model = Company fields = ['name', 'subtitle', 'notes'] widgets = { 'notes': forms.Textarea(attrs={ 'rows': 4, 'cols': 22 }), } template_name = "CRM/edit-company.html" def get_success_url(self): return "/companies/"
class ProjectModelForm(forms.ModelForm): title = forms.CharField(label='Titre', max_length=100) thumbnail = forms.ImageField(label="Illustration du projet", required=False) description = forms.CharField( label='Description', required=False, widget=forms.Textarea()) moderation = forms.BooleanField(label='Modération', required=False) is_project_type = forms.BooleanField( label="Est un projet type", required=False) archive_feature = forms.IntegerField( label='Délai avant archivage', required=False) delete_feature = forms.IntegerField( label='Délai avant suppression', required=False) access_level_pub_feature = forms.ModelChoiceField( label='Visibilité des signalements publiés', queryset=UserLevelPermission.objects.filter(rank__lte=2).order_by('rank'), empty_label=None,) access_level_arch_feature = forms.ModelChoiceField( label='Visibilité des signalements archivés', queryset=UserLevelPermission.objects.filter(rank__lte=4).order_by('rank'), empty_label=None,) create_from = forms.CharField(required=False, widget=HiddenInput()) class Meta: model = Project fields = [ 'title', 'description', 'moderation', 'thumbnail', 'access_level_pub_feature', 'access_level_arch_feature', 'archive_feature', 'delete_feature', 'is_project_type', 'create_from', ] def __init__(self, *args, **kwargs): slug = kwargs.pop('create_from', None) project_type = Project.objects.filter(slug=slug).first() super().__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: # Optionnel for key in ['archive_feature', 'delete_feature']: source = getattr(instance, key) self.fields[key].initial = source elif project_type: for key in [ 'archive_feature', 'delete_feature', 'access_level_pub_feature', 'access_level_arch_feature', 'description', 'moderation', 'thumbnail']: source = getattr(project_type, key) self.fields[key].initial = source self.fields['title'].initial = "{} (Copie-{})".format( project_type.title, timezone.now().strftime("%d/%m/%Y %H:%M") ) self.fields['title'].help_text = "Le titre d'un projet doit etre unique. " self.fields['create_from'].initial = slug else: self.fields['archive_feature'].initial = 0 self.fields['delete_feature'].initial = 0 def clean_title(self): title = self.cleaned_data.get('title') if self.instance.pk: if Project.objects.filter(title=title).exclude(pk=self.instance.pk).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) else: if Project.objects.filter(title=title).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) return title def clean(self): cleaned_data = super().clean() archive_feature = cleaned_data.get('archive_feature', None) delete_feature = cleaned_data.get('delete_feature', None) if archive_feature and delete_feature and archive_feature > delete_feature: raise forms.ValidationError({ 'archive_feature': "Le délais de suppression doit être supérieur au délais d'archivage. " }) return cleaned_data
class Meta: model = PermitRequest fields = [ 'administrative_entity', 'address', 'geom', 'description', 'date_start', 'date_end', 'sitetype', 'length', 'width', 'road_marking_damaged', 'is_green_area', 'invoice_to' ] widgets = { 'geom': SitOpenLayersWidget( attrs={ 'map_width': '100%', 'map_height': settings.OL_MAP_HEIGHT, 'map_srid': 2056, 'default_center': [2539057, 1181111], 'default_zoom': 10, 'display_raw': False, #show coordinate in debug 'map_clear_style': "visibility:visible;", 'edit_geom': True, 'min_zoom': 8, 'wmts_capabilities_url': settings.WMTS_GETCAP, 'wmts_layer': settings.WMTS_LAYER, 'wmts_capabilities_url_alternative': settings.WMTS_GETCAP_ALTERNATIVE, 'wmts_layer_alternative': settings.WMTS_LAYER_ALTERNATIVE, 'administrative_entities_url': 'gpf:adm-entity-geojson', }), 'administrative_entity': forms.Select( attrs={ 'onchange': "gpfMap.zoomToAdminEntity(this.options[this.selectedIndex].value);" }), 'date_start': DatePickerInput( options={ "format": "DD/MM/YYYY", "locale": "fr", "minDate": ( datetime.datetime.today() + datetime.timedelta(days=int(settings.MIN_START_DELAY)) ).strftime('%Y/%m/%d') }).start_of('event days'), 'date_end': DatePickerInput( options={ "format": "DD/MM/YYYY", "locale": "fr", "minDate": ( datetime.datetime.today() + datetime.timedelta(days=int(settings.MIN_START_DELAY)) ).strftime('%Y/%m/%d') }).end_of('event days'), 'description': forms.Textarea(attrs={'rows': '3'}), 'zipcode': forms.TextInput(attrs={'id': 'id_zipcode_permit'}), 'city': forms.TextInput(attrs={'id': 'id_city_permit'}), 'address': RemoteAutocompleteWidget( attrs={ "id": "id_adress_permit", "apiurl": "https://api3.geo.admin.ch/rest/services/api/SearchServer?", "apiurl_detail": "https://api3.geo.admin.ch/rest/services/api/MapServer/ch.bfs.gebaeude_wohnungs_register/", "search_prefix": "true", "origins": "address", "zipcode_field": "zipcode_permit", "city_field": "city_permit", "placeholder": "ex: Rue de la plaine", }), }
class EmpleadoForm(forms.Form): cedula = forms.CharField(required=False, label=u'Cédula') nombres = forms.CharField(max_length=250, widget=forms.TextInput(attrs={'size': '30'})) apellido_paterno = forms.CharField( max_length=250, widget=forms.TextInput(attrs={'size': '30'})) apellido_materno = forms.CharField( max_length=250, widget=forms.TextInput(attrs={'size': '30'}), required=False) pais = forms.ModelChoiceField( queryset=Pais.objects.all(), empty_label="Escoger un pais", widget=forms.Select(attrs={ 'placeholder': 'País', 'onChange': "getProvincias(this.value)" })) provincia = forms.ModelChoiceField( queryset=Provincia.objects.none(), empty_label="Escoger una provincia", widget=forms.Select( attrs={ 'placeholder': 'Provincia o estado', 'onChange': "getCiudades(this.value)" })) ciudad = forms.ModelChoiceField( queryset=Ciudad.objects.none(), empty_label="Escoger una ciudad", widget=forms.Select(attrs={'placeholder': 'Ciudad o Cantón'})) sexo = forms.ChoiceField(choices=PersonaNatural.SEXO_CHOICES, required=True) fecha_nacimiento = forms.DateField(required=False) observaciones = forms.CharField(widget=forms.Textarea()) usuario = forms.CharField(max_length=13, widget=forms.TextInput(attrs={'size': '30'})) contrasenia = forms.CharField( max_length=13, widget=forms.PasswordInput(attrs={'size': '30'})) email = forms.EmailField(max_length=25, widget=forms.TextInput(attrs={'size': '30'})) plazas_trabajo = forms.ModelMultipleChoiceField( queryset=PlazaTrabajo.objects.all(), widget=forms.SelectMultiple) foto = forms.ImageField(required=False) def modificarQuerySet(self, pais_id, provincia_id): if pais_id not in ('', None): self.fields['provincia'].queryset = Provincia.objects.filter( pais__id=pais_id) if provincia_id not in ('', None): self.fields['ciudad'].queryset = Ciudad.objects.filter( provincia__id=provincia_id) def save(self, empleado=None): cleaned_data = super(EmpleadoForm, self).clean() if empleado is None: persona = Persona() persona.tipo = Persona.TIPO_PERSONA_NATURAL persona.observaciones = cleaned_data["observaciones"] persona.ruc = cleaned_data["cedula"] persona.nombre_comercial = "" persona.save() usuario = User() usuario.username = cleaned_data["usuario"] usuario.set_password(cleaned_data["contrasenia"]) usuario.email = cleaned_data["email"] usuario.save() persona_natural = PersonaNatural() persona_natural.ciudad_nacimiento = cleaned_data['ciudad'] persona_natural.cedula = cleaned_data["cedula"] persona_natural.nombres = cleaned_data["nombres"] persona_natural.apellido_paterno = cleaned_data["apellido_paterno"] persona_natural.apellido_materno = cleaned_data["apellido_materno"] persona_natural.persona = persona persona_natural.sexo = cleaned_data["sexo"] persona_natural.fecha_nacimiento = cleaned_data["fecha_nacimiento"] persona_natural.save() empleado = Empleado() empleado.persona = persona_natural empleado.usuario = usuario empleado.foto = cleaned_data["foto"] empleado.observaciones = cleaned_data["observaciones"] empleado.save() empleado.plazas_trabajo = cleaned_data["plazas_trabajo"] empleado.save() else: empleado.persona.nombres = cleaned_data["nombres"] empleado.persona.apellido_paterno = cleaned_data[ "apellido_paterno"] empleado.persona.apellido_materno = cleaned_data[ "apellido_materno"] empleado.persona.sexo = cleaned_data["sexo"] empleado.persona.cedula = cleaned_data["cedula"] empleado.persona.ciudad_nacimiento = cleaned_data["ciudad"] empleado.persona.save() empleado.usuario.email = cleaned_data["email"] empleado.usuario.save() empleado.foto = cleaned_data["foto"] empleado.observaciones = cleaned_data["observaciones"] empleado.save() empleado.plazas_trabajo = cleaned_data["plazas_trabajo"] empleado.save() return empleado def clean_usuario(self): if self.cleaned_data['usuario']: p = User.objects.filter(username=self.cleaned_data['usuario']) if len(p) > 0: raise forms.ValidationError( _("Ya esxiste un usuario con este username")) return self.cleaned_data['usuario']
class Meta: model = Validation fields = '__all__' widgets = { 'comment': forms.Textarea(attrs={'rows': '3'}), }
class Meta: model = Venue exclude = ['slug'] widgets = {'description': forms.Textarea(attrs={'rows': 3})} labels = {'title': 'Venue Name', 'url': 'URL'}
class ProjectModelForm(forms.ModelForm): title = forms.CharField(label='Titre', max_length=100) thumbnail = forms.ImageField(label="Illustration du projet", required=False) description = forms.CharField(label='Description', required=False, widget=forms.Textarea()) moderation = forms.BooleanField(label='Modération', required=False) archive_feature = forms.IntegerField(label='Délai avant archivage', required=False) delete_feature = forms.IntegerField(label='Délai avant suppression', required=False) access_level_pub_feature = forms.ModelChoiceField( label='Visibilité des signalements publiés', queryset=UserLevelPermission.objects.filter( rank__lte=2).order_by('rank'), empty_label=None, ) access_level_arch_feature = forms.ModelChoiceField( label='Visibilité des signalements archivés', queryset=UserLevelPermission.objects.filter( rank__lte=4).order_by('rank'), empty_label=None, ) class Meta: model = Project fields = [ 'title', 'description', 'moderation', 'thumbnail', 'access_level_pub_feature', 'access_level_arch_feature', 'archive_feature', 'delete_feature', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: self.fields['archive_feature'].initial = instance.archive_feature self.fields['delete_feature'].initial = instance.delete_feature else: self.fields['archive_feature'].initial = 0 self.fields['delete_feature'].initial = 0 def clean_title(self): title = self.cleaned_data.get('title') if self.instance.pk: if Project.objects.filter(title=title).exclude( pk=self.instance.pk).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) else: if Project.objects.filter(title=title).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) return title def clean(self): cleaned_data = super().clean() archive_feature = cleaned_data.get('archive_feature', None) delete_feature = cleaned_data.get('delete_feature', None) if archive_feature and delete_feature and archive_feature > delete_feature: raise forms.ValidationError( "Le délai d'archivage doit être inférieur au délai de suppression. " ) return cleaned_data
class Meta: model = PermitRequest exclude = [] fields = [ 'company', 'project_owner', 'ended', 'archeotype', 'has_archeology', 'amount', 'paid', 'validated', 'sent', 'date_start', 'date_end', 'date_end_work_announcement', 'date_end_work', 'date_request_created', 'road_marking_damaged', 'is_green_area', 'invoice_to', 'sitetype', 'description', 'administrative_entity', 'address', 'length', 'width', 'geom' ] help_texts = { 'validated': "Par le secrétariat uniquement", 'archeotype': "Zone archéologique observée au moment de la fouille", 'has_archeology': "Zone archéologique détectée sur la base des géodonnées cantonales", 'ended': "La fouille a-t-elle été contrôlée par le bureau STE ?", } widgets = { 'geom': SitOpenLayersWidget( attrs={ 'map_width': '100%', 'map_height': settings.OL_MAP_HEIGHT, 'map_srid': 2056, 'default_center': [2539057, 1181111], 'default_zoom': 10, 'display_raw': False, #show coordinate in debug 'map_clear_style': "visibility:visible;", 'edit_geom': False, 'min_zoom': 6, 'wmts_capabilities_url': settings.WMTS_GETCAP, 'wmts_layer': settings.WMTS_LAYER, 'wmts_capabilities_url_alternative': settings.WMTS_GETCAP_ALTERNATIVE, 'wmts_layer_alternative': settings.WMTS_LAYER_ALTERNATIVE, 'administrative_entities_url': 'gpf:adm-entity-geojson', }), 'administrative_entity': forms.Select( attrs={ 'onchange': "gpfMap.zoomToAdminEntity(this.options[this.selectedIndex].value);" }), 'date_start': DatePickerInput(options={ "format": "DD/MM/YYYY", "locale": "fr" }).start_of('event days'), 'date_end': DatePickerInput(options={ "format": "DD/MM/YYYY", "locale": "fr" }).end_of('event days'), 'date_end_work': DatePickerInput(options={ "format": "DD/MM/YYYY", "locale": "fr" }), 'date_end_work_announcement': DatePickerInput(options={ "format": "DD/MM/YYYY", "locale": "fr" }, ), 'date_request_created': forms.TextInput(attrs={'readonly': 'readonly'}), 'description': forms.Textarea(attrs={'rows': '3'}), 'address': RemoteAutocompleteWidget( attrs={ "apiurl": "https://api3.geo.admin.ch/rest/services/api/SearchServer?", "apiurl_detail": "https://api3.geo.admin.ch/rest/services/api/MapServer/ch.bfs.gebaeude_wohnungs_register/", "search_prefix": "true", "origins": "address", "zipcode_field": "zipcode", "city_field": "city", "placeholder": "ex: Place Pestalozzi 2 Yverdon", }), }