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 BasicInformationForm(forms.ModelForm): """Form for Basic Information model.""" name = forms.CharField( required=True, label='Your name', widget=forms.TextInput(attrs={'placeholder': 'John Doe'})) email = forms.EmailField( required=True, label='Your email', widget=forms.EmailInput(attrs={ 'readonly': 'readonly', 'placeholder': '*****@*****.**' })) image = forms.ImageField(required=False, widget=CustomClearableFileInput()) website = forms.URLField( required=False, label='Your website', widget=forms.URLInput(attrs={'placeholder': 'http://john.doe.com'})) inasafe_roles = forms.ModelMultipleChoiceField( required=True, label='Your InaSAFE role(s)', queryset=InasafeRole.objects.filter(sort_number__gte=1), widget=forms.CheckboxSelectMultiple) osm_roles = forms.ModelMultipleChoiceField( required=False, label='Your OSM role(s)', queryset=OsmRole.objects.filter(sort_number__gte=1), widget=forms.CheckboxSelectMultiple) osm_username = forms.CharField( required=False, label='OSM Username', widget=forms.TextInput(attrs={'placeholder': 'johndoe'})) email_updates = forms.BooleanField( required=False, label='Receive project news and updates') location = forms.PointField(label='Click your location on the map', widget=LeafletWidget()) class Meta: """Association between models and this form.""" model = User fields = [ 'name', 'email', 'image', 'website', 'inasafe_roles', 'osm_roles', 'osm_username', 'location', 'email_updates' ] def save(self, commit=True): """Save form. :param commit: Whether committed to db or not. :type commit: bool """ user = super(BasicInformationForm, self).save(commit=False) if commit: user.save() return user
class CompanyForm(forms.Form): name = forms.CharField(max_length=200, label='Company name') logo = forms.ImageField(label='Logo') description = forms.CharField(widget=forms.Textarea) location = forms.PointField(widget=forms.OSMWidget(attrs={'map_width': 700, 'map_height': 500})) category = forms.ChoiceField(choices=categories) # TODO put list help_message = forms.CharField(widget=forms.Textarea, label='How can I get help') # blank=True opening_hours = forms.CharField() # max_length=400, blank=True cover = forms.ImageField(label='Cover picture') other_image1 = forms.ImageField(label='Other image # 1', required=False) other_image2 = forms.ImageField(label='Other image # 2', required=False) other_image3 = forms.ImageField(label='Other image # 3', required=False) # services service1_cat = forms.ChoiceField(choices=service_categories, label='Service # 1 category') service1_desc = forms.CharField(widget=forms.Textarea, label='Service # 1 description', required=False) service2_cat = forms.ChoiceField(choices=service_categories, label='Service # 2 category') service2_desc = forms.CharField(widget=forms.Textarea, label='Service # 2 description', required=False) service3_cat = forms.ChoiceField(choices=service_categories, label='Service # 3 category') service3_desc = forms.CharField(widget=forms.Textarea, label='Service # 3 description', required=False)
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 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 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 RegistrationForm(forms.ModelForm): """Form for user model.""" name = forms.CharField( required=True, label='Name', widget=forms.TextInput(attrs={'placeholder': 'John Doe'})) email = forms.EmailField( required=True, label='Email', widget=forms.EmailInput(attrs={'placeholder': '*****@*****.**'})) image = forms.ImageField(required=False, widget=CustomClearableFileInput()) password = forms.CharField(required=True, label='Password', widget=forms.PasswordInput()) password2 = forms.CharField(required=True, label='Password (again)', widget=forms.PasswordInput()) website = forms.URLField( required=False, label='Website', widget=forms.URLInput(attrs={'placeholder': 'http://john.doe.com'})) inasafe_roles = forms.ModelMultipleChoiceField( required=True, label='Your InaSAFE role(s)', queryset=InasafeRole.objects.all(), widget=forms.CheckboxSelectMultiple) osm_roles = forms.ModelMultipleChoiceField( required=False, label='Your OSM role(s)', queryset=OsmRole.objects.all(), widget=forms.CheckboxSelectMultiple) osm_username = forms.CharField( required=False, label='OSM Username', widget=forms.TextInput(attrs={'placeholder': 'johndoe'})) location = forms.PointField( label='Draw a marker as your location on the map', widget=LeafletWidget()) email_updates = forms.BooleanField( required=False, label='Receive project news and updates') class Meta: """Association between models and this form.""" model = User fields = [ 'name', 'email', 'image', 'password', 'password2', 'website', 'inasafe_roles', 'osm_roles', 'osm_username', 'location', 'email_updates' ] def clean(self): """Verifies that the values entered into the password fields match.""" cleaned_data = super(RegistrationForm, self).clean() if 'password' in cleaned_data and 'password2' in cleaned_data: if cleaned_data['password'] != cleaned_data['password2']: raise forms.ValidationError( "Passwords don't match. Please enter both fields again.") return cleaned_data def save(self, commit=True): """Save form. :param commit: Whether committed to db or not. :type commit: bool """ user = super(RegistrationForm, self).save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user