class Meta: model = Profile fields = ('profile_image', 'phone', 'address') widgets = {'profile_image': forms.FileInput()}
class UploadImageForm(forms.Form): image = forms.ImageField(widget=forms.FileInput( attrs={"class": "custom-file-input"}))
class ImageForm(ModelForm): file = forms.ImageField(widget=forms.FileInput(attrs={'multiple': True},)) class Meta: model = Image fields = ['file',]
class RegistrationForm(forms.ModelForm): avatar = forms.ImageField(required=False, widget=forms.FileInput()) check_password = forms.CharField(label=_("Repeat Password"), widget=forms.PasswordInput()) avatar.widget.attrs.update({ "id": "avatar-field", }) check_password.widget.attrs.update({ "id": "check-password-field", "class": "auth-field", "autocomplete": "off", "placeholder": _("Repeat Password") }) class Meta: model = User fields = ("username", "email", "password") widgets = { "username": forms.TextInput( attrs={ "id": "username-field", "class": "auth-field", "autocomplete": "off", "spellcheck": "false", "autofocus": True, "placeholder": _("Username") }), "email": forms.EmailInput( attrs={ "id": "email-field", "class": "auth-field", "autocomplete": "off", "placeholder": _("Email") }), "password": forms.PasswordInput( attrs={ "id": "password-field", "class": "auth-field", "autocomplete": "off", "placeholder": _("Password") }) } labels = { "username": "******", "email": "Email", "password": _("Password") } def clean(self): cleaned_data = super().clean() password = cleaned_data["password"] check_password = cleaned_data["check_password"] if password != check_password: raise forms.ValidationError(_("Passwords do not match")) return cleaned_data
class UploadForm(forms.Form): fichier = forms.FileField(widget=forms.FileInput(attrs={'id': 'file-0a', 'class': 'file'}), label='Selectionner un fichier...' ) k = forms.IntegerField(validators=[MinValueValidator(1)]) n = forms.IntegerField(validators=[MinValueValidator(1)])
class UploadFileForm(forms.Form): file = forms.FileField( label='CSV-файл', widget=forms.FileInput(attrs={'accept': 'text/csv'}), )
class SubmissionForm(forms.ModelForm): SCALE_PRESET_SETTINGS = { '1': (0.1, 180), '2': (1, 180), '3': (10, 180), '4': (0.05, 0.15) } file = forms.FileField(required=False, widget=forms.FileInput(attrs={ 'size': '80', 'style': 'border:0px' })) url = forms.CharField(widget=forms.TextInput(attrs={'size': '80'}), initial='http://', required=False) upload_type = forms.ChoiceField( widget=forms.RadioSelect(renderer=HorizontalRenderer), choices=(('file', 'file'), ('url', 'url')), initial='file') scale_preset = forms.ChoiceField( widget=forms.RadioSelect(renderer=NoBulletsRenderer), choices=(('1', 'default (0.1 to 180 degrees)'), ('2', 'wide field (1 to 180 degrees)'), ('3', 'very wide field (10 to 180 degrees)'), ('4', 'tiny (3 to 9 arcmin)'), ('5', 'custom')), initial='1') album = forms.ChoiceField(choices=(), required=False) new_album_title = forms.CharField( widget=forms.TextInput(attrs={'size': '40'}), max_length=64, required=False) allow_commercial_use = forms.ChoiceField( widget=forms.RadioSelect(renderer=NoBulletsRenderer), choices=License.YES_NO, initial='d', ) allow_modifications = forms.ChoiceField( widget=forms.RadioSelect(renderer=NoBulletsRenderer), choices=License.YES_SA_NO, initial='d', ) advanced_settings = forms.BooleanField(widget=forms.HiddenInput(), initial=False, required=False) class Meta: model = Submission fields = ( 'publicly_visible', #'allow_commercial_use', 'allow_modifications', 'parity', 'scale_units', 'scale_type', 'scale_lower', 'scale_upper', 'scale_est', 'scale_err', 'positional_error', 'center_ra', 'center_dec', 'radius', 'tweak_order', 'downsample_factor', 'use_sextractor', 'crpix_center', 'invert', #'source_type' ) widgets = { 'scale_type': forms.RadioSelect(renderer=HorizontalRenderer), 'scale_lower': forms.TextInput(attrs={'size': '5'}), 'scale_upper': forms.TextInput(attrs={'size': '5'}), 'scale_est': forms.TextInput(attrs={'size': '5'}), 'scale_err': forms.TextInput(attrs={'size': '5'}), 'positional_error': forms.TextInput(attrs={'size': '5'}), 'center_ra': forms.TextInput(attrs={'size': '5'}), 'center_dec': forms.TextInput(attrs={'size': '5'}), 'radius': forms.TextInput(attrs={'size': '5'}), 'tweak_order': forms.TextInput(attrs={'size': 5}), 'downsample_factor': forms.TextInput(attrs={'size': '5'}), 'use_sextractor': forms.CheckboxInput(), 'crpix_center': forms.CheckboxInput(), 'invert': forms.CheckboxInput(), 'parity': forms.RadioSelect(renderer=NoBulletsRenderer), #'source_type': forms.RadioSelect(renderer=NoBulletsRenderer), 'publicly_visible': forms.RadioSelect(renderer=NoBulletsRenderer), #'allow_commercial_use':forms.RadioSelect(renderer=NoBulletsRenderer), #'allow_modifications':forms.RadioSelect(renderer=NoBulletsRenderer), } def clean(self): number_message = "Enter a number." scale_preset = self.cleaned_data.get('scale_preset', '') if scale_preset == '5': # custom preset error handling scale_type = self.cleaned_data.get('scale_type', '') if scale_type == 'ul': scale_lower = self.cleaned_data.get('scale_lower') scale_upper = self.cleaned_data.get('scale_upper') if not scale_lower: self._errors['scale_lower'] = self.error_class( [number_message]) if not scale_upper: self._errors['scale_upper'] = self.error_class( [number_message]) elif scale_type == 'ev': scale_est = self.cleaned_data.get('scale_est') scale_err = self.cleaned_data.get('scale_err') if not scale_est: self._errors['scale_est'] = self.error_class( [number_message]) if not scale_err: self._errors['scale_err'] = self.error_class( [number_message]) else: # if scale isn't custom, use preset settings self.cleaned_data['scale_type'] = 'ul' self.cleaned_data['scale_units'] = 'degwidth' self.cleaned_data['scale_lower'] = self.SCALE_PRESET_SETTINGS[ scale_preset][0] self.cleaned_data['scale_upper'] = self.SCALE_PRESET_SETTINGS[ scale_preset][1] center_ra = self.cleaned_data.get('center_ra') center_dec = self.cleaned_data.get('center_dec') radius = self.cleaned_data.get('radius') if center_ra or center_dec or radius: if not center_ra: self._errors['center_ra'] = self.error_class([number_message]) if not center_dec: self._errors['center_dec'] = self.error_class([number_message]) if not radius: self._errors['radius'] = self.error_class([number_message]) tweak_order = self.cleaned_data.get('tweak_order') if tweak_order < 0 or tweak_order > 9: self._errors['tweak_order'] = self.error_class( ['Tweak order must be between 0 and 9']) upload_type = self.cleaned_data.get('upload_type', '') if upload_type == 'file': if not self.cleaned_data.get('file'): raise forms.ValidationError( "You must select a file to upload.") elif upload_type == 'url': url = self.cleaned_data.get('url', '') if not (url.startswith('http://') or url.startswith('ftp://')): url = 'http://' + url if url.startswith('http://http://') or url.startswith( 'http://ftp://'): url = url[7:] if len(url) == 0: raise forms.ValidationError("You must enter a url to upload.") urlvalidator = URLValidator() try: urlvalidator(url) except forms.ValidationError: raise forms.ValidationError("You must enter a valid url.") self.cleaned_data['url'] = url return self.cleaned_data def __init__(self, user, *args, **kwargs): super(SubmissionForm, self).__init__(*args, **kwargs) #if user.is_authenticated(): # self.fields['album'].queryset = user.albums self.fields['album'].choices = [('', 'none')] if user.is_authenticated(): for album in Album.objects.filter(user=user).all(): self.fields['album'].choices += [(album.id, album.title)] self.fields['album'].choices += [('new', 'create new album...')] self.fields['album'].initial = ''
class ProfileAgencyForm(forms.Form): myfile = forms.ImageField(required=False, widget=forms.FileInput( attrs={ 'visibility': 'hidden', 'position': 'absolute', 'top': '-9999px', 'left': '-9999px', 'onchange': 'showImage()', 'data-show-upload': 'false', 'data-show-caption': 'false', 'data-show-remove': 'false', 'data-browse-class': 'btn btn-default', 'data-browse-label': 'Browse Images', 'accept': 'image/jpeg,image/png', })) Agency_Name = forms.CharField( max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Address_Line_1 = forms.CharField( max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Address_Line_2 = forms.CharField( max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) City = forms.CharField(max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Phone = forms.CharField(max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Email = forms.EmailField(max_length=254, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Website = forms.CharField(max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) bio = forms.CharField(required=False, max_length=2000, widget=forms.Textarea(attrs={ 'class': 'form-control', 'rows': '4' })) skype = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', })) twitter = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', })) facebook = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', })) Pintrest = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', })) def clean(self): cleaned_data = super(ProfileAgencyForm, self).clean() name = cleaned_data.get('Agency_Name') email = cleaned_data.get('Email') message = cleaned_data.get('Phone') if not name and not email and not message: raise forms.ValidationError('You have to write something!')
class PropEdit(forms.Form): choiceprop = [ "Property Type", "Apartment", "Cottage", "Condonium", "Cottage", "Flat", "House" ] Property_type = forms.ChoiceField(choices=[(o, str(o)) for o in choiceprop]) choize = [ "Towns", "Chadiza", "Chama", "Chambeshi", "Chavuma", "Chembe", "Chibombo", "Chiengi", "Chilubi", "Chinsali", "Chinyingi", "Chirundu", "Chisamba", "Choma", "Gwembe", "Isoka", "Kabompo", "Kafue", "Kafulwe", "Kalabo", "Kalene Hill", "Kalomo", "Kalulushi", "Kanyembo", "Kaoma", "Kapiri Mposhi", "Kasempa", "Kashikishi", "Kataba", "Katete", "Kawambwa", "Kazembe", "Kazungula", "Kibombomene", "Luangwa", "Lufwanyama", "Lukulu", "Lundazi", "Macha Mission", "Makeni" "Maliti", "Mansa", "Mazabuka", "Mbala", "Mbereshi", "Mfuwe", "Milenge", "Misisi", "Mkushi", "Mongu", "Monze", "Mpika", "Mporokoso", "Mpulungu", "Mumbwa", "Muyombe", "Mwinilunga", "Nchelenge", "Ngoma", "Nkana", "Nseluka", "Pemba", "Petauke", "Samfya", "Senanga", "Serenje", "Sesheke", "Shiwa Ngandu", "Siavonga", "Sikalongo", "Sinazongwe", "Zambezi", "Zimba" ] town = forms.ChoiceField(choices=[(o, str(o)) for o in choize]) choize = [ "provinces", "Copperbelt", "Luapula", "Muchinga", "North-Western", "Western", "Southern", "Central", "Lusaka", "Eastern", "Northern" ] provinces = forms.ChoiceField(choices=[(o, str(o)) for o in choize]) choice = [ "City", "Lusaka", "Ndola", "Kitwe", "Kabwe", "Chingola", "Mufulira", "Livingstone", "Luanshya", "Kasama", "Chipata" ] # js.index() city = forms.ChoiceField(choices=[(o, str(o)) for o in choice]) #prop_id = forms.IntegerField(widget=forms.NumberInput()) video = forms.CharField(required=False, widget=forms.TextInput(attrs={ 'class': 'form-control', })) myfile = forms.ImageField(required=False, widget=forms.FileInput( attrs={ 'visibility': 'hidden', 'position': 'absolute', 'top': '-9999px', 'left': '-9999px', 'onchange': 'showImage()', 'data-show-upload': 'false', 'data-show-caption': 'false', 'data-show-remove': 'false', 'data-browse-class': 'btn btn-default', 'data-browse-label': 'Browse Images', 'accept': 'image/jpeg,image/png', })) title = forms.CharField(max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) price = forms.IntegerField(widget=forms.NumberInput( attrs={ 'class': 'form-control', })) address = forms.CharField(max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', })) baths = forms.IntegerField() beds = forms.IntegerField() area = forms.IntegerField() garages = forms.IntegerField(required=False) description = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={ 'class': 'form-control', }), ) tags = forms.CharField( required=False, max_length=2000, widget=forms.Textarea(attrs={ 'class': 'form-control', 'rows': '2', 'onkeyup': 'tag()', })) choice = ["sale", "rent"] # js.index() status = forms.ChoiceField(choices=[(o, str(o)) for o in choice]) choice = ["Cash", "Debit"] # js.index() payment_option = forms.ChoiceField(choices=[(o, str(o)) for o in choice]) choiceprop = [ "Apartment", "Cottage", "Condonium", "Cottage", "Flat", "House" ] Property_type = forms.ChoiceField(choices=[(o, str(o)) for o in choiceprop]) CHOICES = ( ("True", "True"), ("False", "False"), ) Allow_User_rating = forms.ChoiceField( choices=CHOICES, required=False, widget=forms.CheckboxInput(attrs={ #'style': 'position: absolute; opacity: 0;' })) def clean(self): cleaned_data = super(PropEdit, self).clean() name = cleaned_data.get('title') email = cleaned_data.get('price') message = cleaned_data.get('baths') if not name and not email and not message: raise forms.ValidationError('You have to write something!')
class AbstractTicketForm(CustomFieldMixin, forms.Form): """ Contain all the common code and fields between "TicketForm" and "PublicTicketForm". This Form is not intended to be used directly. """ queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=()) title = forms.CharField( max_length=100, required=True, widget=forms.TextInput(attrs={'class': 'form-control'}), label=_('Summary of the problem'), ) body = forms.CharField( widget=forms.Textarea(attrs={'class': 'form-control'}), label=_('Description of your issue'), required=True, help_text=_( 'Please be as descriptive as possible and include all details'), ) priority = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), choices=Ticket.PRIORITY_CHOICES, required=True, initial=getattr(settings, 'HELPDESK_PUBLIC_TICKET_PRIORITY', '3'), label=_('Priority'), help_text=_( "Please select a priority carefully. If unsure, leave it as '3'."), ) due_date = forms.DateTimeField( widget=forms.TextInput(attrs={'class': 'form-control'}), required=False, input_formats=[ '%d/%m/%Y', '%m/%d/%Y', "%d.%m.%Y", ], label=_('Due on'), ) attachment = forms.FileField( widget=forms.FileInput(attrs={'class': 'form-control-file'}), required=False, label=_('Attach File'), help_text= _('You can attach a file such as a document or screenshot to this ticket.' ), ) def __init__(self, kbcategory=None, *args, **kwargs): super().__init__(*args, **kwargs) if kbcategory: self.fields['kbitem'] = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), required=False, label=_('Knowledge Base Item'), choices=[(kbi.pk, kbi.title) for kbi in KBItem.objects.filter( category=kbcategory.pk, enabled=True)], ) def _add_form_custom_fields(self, staff_only_filter=None): if staff_only_filter is None: queryset = CustomField.objects.all() else: queryset = CustomField.objects.filter(staff_only=staff_only_filter) for field in queryset: instanceargs = { 'label': field.label, 'help_text': field.help_text, 'required': field.required, } self.customfield_to_field(field, instanceargs) def _get_queue(self): # this procedure is re-defined for public submission form return Queue.objects.get(id=int(self.cleaned_data['queue'])) def _create_ticket(self): queue = self._get_queue() kbitem = None if 'kbitem' in self.cleaned_data: kbitem = KBItem.objects.get(id=int(self.cleaned_data['kbitem'])) ticket = Ticket( title=self.cleaned_data['title'], submitter_email=self.cleaned_data['submitter_email'], created=timezone.now(), status=Ticket.OPEN_STATUS, queue=queue, description=self.cleaned_data['body'], priority=self.cleaned_data.get( 'priority', getattr(settings, "HELPDESK_PUBLIC_TICKET_PRIORITY", "3")), due_date=self.cleaned_data.get( 'due_date', getattr(settings, "HELPDESK_PUBLIC_TICKET_DUE_DATE", None)) or None, kbitem=kbitem, ) return ticket, queue def _create_custom_fields(self, ticket): for field, value in self.cleaned_data.items(): if field.startswith('custom_'): field_name = field.replace('custom_', '', 1) custom_field = CustomField.objects.get(name=field_name) cfv = TicketCustomFieldValue(ticket=ticket, field=custom_field, value=value) cfv.save() def _create_follow_up(self, ticket, title, user=None): followup = FollowUp( ticket=ticket, title=title, date=timezone.now(), public=True, comment=self.cleaned_data['body'], ) if user: followup.user = user return followup def _attach_files_to_follow_up(self, followup): files = self.cleaned_data['attachment'] if files: files = process_attachments(followup, [files]) return files @staticmethod def _send_messages(ticket, queue, followup, files, user=None): context = safe_template_context(ticket) context['comment'] = followup.comment roles = { 'submitter': ('newticket_submitter', context), 'new_ticket_cc': ('newticket_cc', context), 'ticket_cc': ('newticket_cc', context) } if ticket.assigned_to and ticket.assigned_to.usersettings_helpdesk.email_on_ticket_assign: roles['assigned_to'] = ('assigned_owner', context) ticket.send( roles, fail_silently=True, files=files, )
class NewJobForm(forms.Form): job_name = forms.CharField( label='Job Name', widget=forms.TextInput(attrs={'readonly': True})) job_input = forms.FileField( label='Input Files', widget=forms.FileInput(attrs={'required': True}))
class UploadFileForm(forms.Form): file = forms.FileField(label='', widget=forms.FileInput(attrs={}))
class ContributorUploadForm(forms.ModelForm): """ Fields are: class_number: This will be class number like first, second .. eight .. tenth. name: This field is the name of the subject,the contributor is specialized in. topic: The subject of the topic the contibutor is going to contribute. pdf: The contributor has to upload the files.This field describes that the uploaded file must be a pdf file. video: The contributor has to upload the files.This field describes that the uploaded file must be a video. May be mp4. animation: The contributor has to upload the files.This field describes that the uploaded file must be an animation file. This may be gif. summary: This is the summary given by the contributor about the specified topic of the specified subject including when to use and how to use. """ language = forms.ModelChoiceField( label='Language', cache_choices=True, widget=None, queryset=Language.objects.all(), empty_label=None, help_text="", required=True, error_messages={'required': 'Language is required'}) class_number = forms.ModelChoiceField( label='Class', cache_choices=True, widget=None, queryset=Class.objects.all(), empty_label=None, help_text="", required=True, error_messages={'required': 'Class is required'}) name = forms.CharField( widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Subject name*.' }), help_text="", required=True, error_messages={'required': 'Subject name is required.'}) topic = forms.CharField( widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Subject topic*.' }), help_text="", required=True, error_messages={'required': 'Subject topic is required.'}) pdf = forms.FileField(label='pdf file.', widget=forms.FileInput(), help_text='Upload pdf file.', required=False) video = forms.FileField(label='video file.', help_text='Upload video file.', required=False) animation = forms.FileField(label='animations file.', widget=forms.FileInput(), help_text='Upload animations file.', required=False) summary = forms.CharField( label='Summary', widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'Summary for the uploaded documents.' }), help_text="", required=True, error_messages={'required': 'Summary is required.'}) class Meta: model = Subject fields = [ 'language', 'class_number', 'name', 'topic', 'pdf', 'video', 'animation', 'summary' ] def clean_pdf(self): """Upload a valid.""" if self.cleaned_data['pdf']: pdf = self.cleaned_data['pdf'] print pdf.content_type.split('/')[1] if pdf.content_type.split('/')[1] in ( "pdf", "vnd.oasis.opendocument.presentation", "vnd.openxmlformats-officedocument.wordprocessingml.document", "vnd.oasis.opendocument.text", "vnd.ms-powerpoint", "vnd.openxmlformats-officedocument.presentationml.presentation" ): if pdf._size / (1024 * 1024) <= 20: # < 20MB return pdf else: raise forms.ValidationError("PDF file max. size is 20MB.") else: raise forms.ValidationError("Not a valid pdf file!") def clean_video(self): """Limit doc_file upload size.""" if self.cleaned_data['video']: video = self.cleaned_data['video'] if video.content_type.split('/')[1] in ("mp4", "x-matroska", "x-msvideo", "x-flv"): if video._size / (1024 * 1024) <= 200: # < 100MB return video else: raise forms.ValidationError("File max. size is 100MB.") else: raise forms.ValidationError("Not a valid video file") def clean_animation(self): """Limit doc_file upload size.""" if self.cleaned_data['animation']: animation = self.cleaned_data['animation'] if animation.content_type.split('/')[1] == "x-shockwave-flash": if animation._size / (1024 * 1024) <= 10: # < 10MB return animation else: raise forms.ValidationError("File max. size is 10MB.") else: raise forms.ValidationError("Not a valid file!")
class Meta: model = Profile fields = ['nickname','gender','intro','image'] widgets = { 'image': forms.FileInput(attrs={'class': 'form-control-file'}) }
class CreateProductForm(forms.ModelForm): foto = forms.ImageField(label="Imagen",validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])], required=False, widget=forms.FileInput(attrs={'style':'display:None', 'accept':'image/*'})) nombre = forms.CharField(label='Nombre',error_messages={'required':'Este campo no puede estar vacío'}, widget=forms.TextInput(attrs={'class' : 'form-control'}) ) descripcion = forms.CharField(label='Descripción',error_messages={'required':'Este campo no puede estar vacío'}, widget= forms.Textarea(attrs={'class' : 'form-control', 'style':'width : 100%', 'blank':'False'})) precio = forms.DecimalField(label="Precio",max_digits=4, decimal_places=2, min_value=0.01, max_value=99.99, widget=forms.NumberInput(attrs={'class':'form-control'})) dieta = forms.ModelMultipleChoiceField(label='Etiqueta', queryset=Dieta.objects.all(), widget=forms.SelectMultiple(attrs={'class' : 'form-control', 'style':'width : 100%'})) categoria = forms.ModelMultipleChoiceField(label='Categoría', queryset=Categoria.objects.all(), widget=forms.SelectMultiple(attrs={'class' : 'form-control', 'style':'width : 100%'})) # Valores nutricionales calorias = forms.IntegerField(min_value=0, max_value=1100, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) grasas = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) grasas_saturadas = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) hidratos = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) azucares = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) fibra = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) proteinas = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) sal = forms.DecimalField(min_value=Decimal('0.00'), max_digits=5, decimal_places=2, required=False, widget=forms.NumberInput(attrs={'class' : 'form-control', 'style':'width : 100%'})) mayorEdad = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'class' : 'form-check-input'})) ubicaciones = CustomMMCF(queryset=Ubicacion.objects.all(), required=False, widget=forms.Select(attrs={'class' : 'form-control', 'style':'width : 100%'})) class Meta: model = Ubicacion fields = ['nombre'] nombreComercio = forms.CharField(label='Nombre del Comercio',strip=True, required=False, widget=forms.TextInput(attrs={'class' : 'form-control'}) ) lat = forms.DecimalField(label='Latitud', widget=forms.HiddenInput, required=False ) lon = forms.DecimalField(label='Longitud', widget=forms.HiddenInput ,required=False) def clean_grasas_saturadas(self): grasas_saturadas = self.cleaned_data['grasas_saturadas'] grasas = self.cleaned_data['grasas'] if grasas_saturadas != None and grasas != None and grasas_saturadas > grasas: raise ValidationError("El producto no puede tener más grasas saturadas que grasas en general.") return grasas_saturadas def clean_azucares(self): azucares = self.cleaned_data['azucares'] hidratos = self.cleaned_data['hidratos'] if azucares != None and hidratos != None and azucares > hidratos: raise ValidationError("El producto no puede tener más azúcares que hidratos de carbono.") return azucares
class PropertyCreate(forms.Form): title = forms.CharField(max_length=30, widget=forms.TextInput(attrs={ 'class': 'form-control', })) price = forms.IntegerField(widget=forms.NumberInput( attrs={ 'class': 'form-control', })) baths = forms.IntegerField() beds = forms.IntegerField() area = forms.IntegerField() garages = forms.IntegerField(required=False) latitude = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={ 'class': 'form-control', 'readonly': 'true', })) longitude = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={ 'class': 'form-control', 'readonly': 'true', 'visibility': 'hidden', })) package = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'form-control', 'readonly': 'true', 'visibility': 'hidden', })) description = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={ 'class': 'form-control', }), ) image = forms.ImageField(required=False, widget=forms.FileInput( attrs={ 'class': 'file', 'multiple': 'true', 'data-show-upload': 'false', 'data-show-caption': 'false', 'data-show-remove': 'false', 'data-browse-class': 'btn btn-default', 'data-browse-label': 'Browse Images', 'accept': 'image/jpeg,image/png', })) choice = ["sale", "rent"] # js.index() status = forms.ChoiceField(choices=[(o, str(o)) for o in choice]) choiceprop = [ "Apartment", "Cottage", "Condonium", "Cottage", "Flat", "House" ] Property_type = forms.ChoiceField(choices=[(o, str(o)) for o in choiceprop]) Allow_User_rating = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style': 'position: absolute; opacity: 0;' })) Air_conditioning = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) bedding = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) heating = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) garrage = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Toaster = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Parquet = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Beach = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Garrage = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Cable_TV = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) pool = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Balcony = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Hi_Fi = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Bedding = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Microwave = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Toaster = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Balcony = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Smoking_allowed = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Coffee_pot = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) Roof_terrace = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) iron = forms.ChoiceField( required=False, widget=forms.CheckboxInput(attrs={ #'style' :'position: absolute; opacity: 0;' })) def clean(self): cleaned_data = super(PropertyCreate, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') message = cleaned_data.get('description') if not name and not email and not message: raise forms.ValidationError('You have to write something!')
widget=forms.DateInput( attrs={ 'id': 'modified', 'aria-describedby': 'modified_icon', 'icon': 'fa fa-clock-o', }, ), ) FIELD_AVATAR = forms.ImageField( label=_('ADMINISTRATION_MODULE_SECURITY_LOCALUSER_AVATAR'), required=False, widget=forms.FileInput( attrs={ 'id': 'avatar', 'icon': 'fa fa-picture-o', 'id_button_upload': 'avatar-button-upload', 'id_image_upload': 'avatar-image-upload', 'style': 'display: none;', }, ), ) FIELD_FIRST_NAME = forms.CharField( label=_('ADMINISTRATION_MODULE_SECURITY_LOCALUSER_FIRST_NAME'), required=False, min_length=1, max_length=100, validators=[ validators.RegexValidator('^[\w .\-_]+$', message=_('ADMINISTRATION_MODULE_SECURITY_LOCALUSER_VALIDATION Only letters, numbers and special characters dot, -, _ and space.')), ], widget=forms.TextInput( attrs={
class PostalBaseForm(AttachmentSaverMixin, forms.Form): scan_help_text = mark_safe(_("Uploaded scans can be PDF, JPG or PNG. Please make sure to <strong>redact/black out all private information concerning you</strong>.")) publicbody = forms.ModelChoiceField( label=_('Public body'), queryset=PublicBody.objects.all(), widget=PublicBodySelect ) date = forms.DateField( widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _('mm/dd/YYYY') }), label=_("Send Date"), help_text=_("Please give the date the reply was sent."), localize=True) subject = forms.CharField(label=_("Subject"), required=False, max_length=230, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": _("Subject")})) text = forms.CharField(label=_("Letter"), widget=forms.Textarea(attrs={"placeholder": _("Letter text"), "class": "form-control" }), required=False, help_text=_("The text can be left empty, instead you can upload scanned documents.")) files = forms.FileField(label=_("Scanned Letter"), required=False, validators=[validate_upload_document], help_text=scan_help_text, widget=forms.FileInput(attrs={'multiple': True})) FIELD_ORDER = ['publicbody', 'date', 'subject', 'text', 'files'] def __init__(self, *args, **kwargs): self.foirequest = kwargs.pop('foirequest') super(PostalBaseForm, self).__init__(*args, **kwargs) self.fields['publicbody'].label = self.PUBLICBODY_LABEL self.fields['publicbody'].initial = self.foirequest.public_body self.order_fields(self.FIELD_ORDER) def clean_date(self): date = self.cleaned_data['date'] now = timezone.now().date() if date > now: raise forms.ValidationError(_("Your reply date is in the future, that is not possible.")) return date def clean_files(self): if '%s-files' % self.prefix not in self.files: return self.cleaned_data['files'] files = self.files.getlist('%s-files' % self.prefix) names = set() for file in files: validate_upload_document(file) name = self.make_filename(file.name) if name in names: # FIXME: dont make this a requirement raise forms.ValidationError(_('Upload files must have distinct names')) names.add(name) return self.cleaned_data['files'] def clean(self): cleaned_data = self.cleaned_data text = cleaned_data.get("text") if '%s-files' % self.prefix in self.files: files = self.files.getlist('%s-files' % self.prefix) else: files = None if not (text or files): raise forms.ValidationError(_("You need to provide either the letter text or a scanned document.")) return cleaned_data def save(self): foirequest = self.foirequest message = FoiMessage( request=foirequest, is_postal=True, ) # TODO: Check if timezone support is correct date = datetime.datetime.combine(self.cleaned_data['date'], datetime.time()) message.timestamp = timezone.get_current_timezone().localize(date) message.subject = self.cleaned_data.get('subject', '') message.subject_redacted = message.redact_subject()[:250] message.plaintext = "" if self.cleaned_data.get('text'): message.plaintext = self.cleaned_data.get('text') message.plaintext_redacted = message.get_content() message = self.contribute_to_message(message) message.save() foirequest.last_message = message.timestamp foirequest.status = 'awaiting_classification' foirequest.save() foirequest.add_postal_reply.send(sender=foirequest) if self.cleaned_data.get('files'): self.save_attachments(self.files.getlist('%s-files' % self.prefix), message) return message
class Meta: model = UploadPG fields = [ 'location', 'pgname', 'pgtype', 'pglocation', 'pgdescription', 'pgprice', 'pgcondition', 'pgmeals', 'ownername', 'pgmobile', 'ammenities1', 'ammenities2', 'ammenities3', 'ammenities4', 'ammenities5', 'ammenities6', 'ammenities7', 'ammenities8', 'ammenities9', 'ammenities10', 'pgimage1', 'pgimage2', 'pgimage3' ] widgets = { 'location': forms.Select(attrs={'class': 'form-control'}), 'pgname': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/FLAT Name' }), 'pgtype': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/FLAT Type' }), 'pglocation': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/FLAT Location' }), 'pgdescription': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/Flat Description' }), 'pgprice': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/FLAT Price' }), 'pgcondition': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter PG/FLAT Condition' }), 'pgmeals': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Meals Included or Not' }), 'ownername': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Owner Name' }), 'pgmobile': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Your Mobile' }), 'ammenities1': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter First Ammenities' }), 'ammenities2': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter second Ammenities' }), 'ammenities3': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Third Ammenities' }), 'ammenities4': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Fourth Ammenities' }), 'ammenities5': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Fifth Ammenities' }), 'ammenities6': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Sixth Ammenities' }), 'ammenities7': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Seventg Ammenities' }), 'ammenities8': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Eighth Ammenities' }), 'ammenities9': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Ninth Ammenities' }), 'ammenities10': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Tenth Ammenities' }), 'pgimage1': forms.FileInput(attrs={'class': 'form-control'}), 'pgimage2': forms.FileInput(attrs={'class': 'form-control'}), 'pgimage3': forms.FileInput(attrs={'class': 'form-control'}), }
class NoTabStopFileField(forms.FileField): widget = forms.FileInput(attrs={"tabindex": "-1"})
def __init__(self, *args, **kwargs): super(UploadXSLTForm, self).__init__(*args, **kwargs) self.fields["name"].label = "Enter XSLT name" self.fields["upload_file"].validators = [ExtensionValidator(".xsl")] self.fields["upload_file"].widget = forms.FileInput( attrs={"accept": ".xslt, .xsl"})
class UploadForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={'size':'70'}))
class ThemeFormAdd(Form): """Form to add a theme.""" required_css_class = 'required' themefile = FileField( label=ugettext_lazy('File'), help_text=ugettext_lazy('The theme.'), widget=forms.FileInput(attrs={'autofocus': True}), ) description = CharField( required=False, max_length=MAX_LENGTH_DESC, label=ugettext_lazy('Description'), ) author = CharField( max_length=MAX_LENGTH_AUTHOR, label=ugettext_lazy('Your name or nick'), help_text=ugettext_lazy('Used for themes page.'), ) mail = EmailField( max_length=MAX_LENGTH_MAIL, label=ugettext_lazy('Your e-mail'), help_text=ugettext_lazy('No spam, never displayed.'), widget=Html5EmailInput(), ) comment = CharField( required=False, max_length=1024, label=ugettext_lazy('Comments'), help_text=ugettext_lazy('Not displayed.'), widget=forms.Textarea(attrs={'rows': '3'}), ) test = TestField( max_length=64, label=ugettext_lazy('Are you a spammer?'), help_text=ugettext_lazy('Enter "no" if you are not a spammer.'), ) def __init__(self, *args, **kwargs): super(ThemeFormAdd, self).__init__(*args, **kwargs) self.label_suffix = '' def clean_themefile(self): """Check if theme file is valid.""" _file = self.cleaned_data['themefile'] if _file.size > 512 * 1024: raise forms.ValidationError(ugettext('Theme file too big.')) props = Theme.get_props(_file.read()) if 'name' not in props or 'weechat' not in props: raise forms.ValidationError(ugettext('Invalid theme file.')) themes = Theme.objects.filter(name=props['name']) if themes: raise forms.ValidationError(ugettext('This name already exists.')) if not props['name'].endswith('.theme'): raise forms.ValidationError( ugettext('Invalid name inside theme file.')) shortname = props['name'][0:-6] if not re.search('^[A-Za-z0-9_]+$', shortname): raise forms.ValidationError( ugettext('Invalid name inside theme file.')) release_stable = Release.objects.get(version='stable') release_devel = Release.objects.get(version='devel') if props['weechat'] not in (release_stable.description, re.sub('-.*', '', release_devel.description)): raise forms.ValidationError( ugettext('Invalid WeeChat version, too old!')) _file.seek(0) return _file
class PostForm(forms.Form): author = forms.CharField(required=False) message = forms.CharField() file = forms.FileInput()
class LocationForm(forms.ModelForm): picture = forms.ImageField(label=_("Picture"), max_length=255, widget=forms.FileInput(), required=False) picture_path = forms.CharField(max_length=255, widget=forms.HiddenInput(), required=False) latitude = forms.FloatField( label=_("Latitude"), help_text= _("Latitude (Lat.) is the angle between any point and the equator (north pole is at 90; south pole is at -90)." ), required=False, ) longitude = forms.FloatField( label=_("Longitude"), help_text= _("Longitude (Long.) is the angle east or west of an arbitrary point on Earth from Greenwich (UK), which is the international zero-longitude point (longitude=0 degrees). The anti-meridian of Greenwich is both 180 (direction to east) and -180 (direction to west)." ), required=False, ) class Meta: model = Location exclude = ["geoposition", "rating"] def __init__(self, request, *args, **kwargs): self.request = request super().__init__(*args, **kwargs) geoposition = self.instance.get_geoposition() if geoposition: self.fields["latitude"].initial = geoposition.latitude self.fields["longitude"].initial = geoposition.longitude name_field = layout.Field("name", css_class="input-block- level") description_field = layout.Field("description", css_class="input-block-level", rows="3") main_fieldset = layout.Fieldset(_("Main data"), name_field, description_field) picture_field = layout.Field( "picture", data_url=reverse("upload_file"), template="core/includes/file_upload_field.html", ) picture_path_field = layout.Field("picture_path") picture_fieldset = layout.Fieldset( _("Picture"), picture_field, picture_path_field, title=_("Picture upload"), css_id="picture_fieldset", ) street_address_field = layout.Field("street_address", css_class="input-block-level") street_address2_field = layout.Field("street_address2", css_class="input-block-level") postal_code_field = layout.Field("postal_code", css_class="input-block-level") city_field = layout.Field("city", css_class="input-block- level") country_field = layout.Field("country", css_class="input- block-level") latitude_field = layout.Field("latitude", css_class="input- block-level") longitude_field = layout.Field("longitude", css_class="input- block-level") address_fieldset = layout.Fieldset( _("Address"), street_address_field, street_address2_field, postal_code_field, city_field, country_field, latitude_field, longitude_field, ) submit_button = layout.Submit("save", _("Save")) actions = bootstrap.FormActions( layout.Div(submit_button, css_class="col")) self.helper = helper.FormHelper() self.helper.form_action = self.request.path self.helper.form_method = "POST" self.helper.attrs = {"noValidate": "noValidate"} self.helper.layout = layout.Layout(main_fieldset, picture_fieldset, address_fieldset, actions) def clean(self): cleaned_data = super().clean() picture_path = cleaned_data["picture_path"] if not self.instance.pk and not self.files.get( "picture") and not picture_path: raise forms.ValidationError(_("Please choose an image.")) def save(self, commit=True): instance = super().save(commit=False) picture_path = self.cleaned_data["picture_path"] if picture_path: temporary_image_path = os.path.join("temporary-uploads", picture_path) file_obj = default_storage.open(temporary_image_path) instance.picture.save(picture_path, file_obj, save=False) default_storage.delete(temporary_image_path) latitude = self.cleaned_data["latitude"] longitude = self.cleaned_data["longitude"] if latitude is not None and longitude is not None: instance.set_geoposition(longitude=longitude, latitude=latitude) if commit: instance.save() self.save_m2m() return instance
class Meta: model = Person fields = ('tc', 'profileImage', 'height', 'weight', 'birthDate', 'bloodType', 'gender', 'birthplace', 'motherName', 'profileImage', 'fatherName') labels = { 'tc': 'T.C.', 'gender': 'Cinsiyet', 'profileImage': 'Profil Resmi' } widgets = { 'profileImage': forms.FileInput(), 'tc': forms.TextInput(attrs={ 'class': 'form-control ', 'required': 'required' }), 'height': forms.TextInput(attrs={'class': 'form-control'}), 'weight': forms.TextInput(attrs={'class': 'form-control'}), 'birthplace': forms.TextInput(attrs={ 'class': 'form-control ', 'value': '', 'required': 'required' }), 'motherName': forms.TextInput(attrs={ 'class': 'form-control ', 'value': '', 'required': 'required' }), 'fatherName': forms.TextInput(attrs={ 'class': 'form-control ', 'value': '', 'required': 'required' }), 'birthDate': forms.DateInput( attrs={ 'class': 'form-control pull-right', 'id': 'datepicker', 'autocomplete': 'off', 'onkeydown': 'return false', 'required': 'required' }), 'bloodType': forms.Select( attrs={ 'class': 'form-control select2 select2-hidden-accessible', 'style': 'width: 100%; ' }), 'gender': forms.Select( attrs={ 'class': 'form-control select2 select2-hidden-accessible', 'style': 'width: 100%;' }), }
class UploadFileForm(forms.Form): file = forms.FileField(widget=forms.FileInput( attrs={'class': 'form-control-file'}))
class WorkshopForm(forms.ModelForm): name = forms.CharField(label='Name', help_text="Name of the workshop", widget=forms.TextInput(attrs={'placeholder': 'Name'})) overview = forms.CharField(label="Overview", help_text="A brief idea about the workshop", widget=forms.Textarea(attrs={'placeholder': 'overview'})) course_details = forms.CharField(label="Details", help_text="Further Details", widget=forms.Textarea(attrs={'placeholder': 'Course Details'})) project = forms.CharField(label="Project", widget=forms.Textarea(attrs={'placeholder': 'Project'})) link = forms.URLField(label="Resources", widget=forms.URLInput(attrs={'placeholder': 'URL'})) other_info = forms.CharField(label="Other Information", widget=forms.Textarea(attrs={'placeholder': 'Other'})) level = forms.CharField(label='Level', widget=forms.TextInput(attrs={'placeholder': 'Level'})) number_of_seats = forms.IntegerField(label='Total number of seats', widget=forms.NumberInput(attrs={'placeholder': '0'})) poster = forms.ImageField(label='Poster', widget=forms.FileInput()) contact_info = forms.CharField(label='Contact', widget=forms.TextInput(attrs={'placeholder': 'Contact'})) start_date_time = forms.DateField(label='From:', widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm", "icons": { "time": "fa fa-clock-o", "date": "fa fa-calendar", "up": "fa fa-arrow-up", "down": "fa fa-arrow-down" }}, attrs={'placeholder': 'YYYY-MM-DD HH:MM'})) end_date_time = forms.DateField(label='To:', widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm", "icons": { "time": "fa fa-clock-o", "date": "fa fa-calendar", "up": "fa fa-arrow-up", "down": "fa fa-arrow-down" }}, attrs={'placeholder': 'YYYY-MM-DD HH:MM'})) price = forms.FloatField(label='Price per head', widget=forms.NumberInput()) def __init__(self, *args, **kwargs): super(WorkshopForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({'class': 'form-control'}) class Meta: model = Workshop fields = ['name', 'overview', 'course_details', 'project', 'link', 'other_info', 'level', 'number_of_seats', 'poster', 'contact_info', 'start_date_time', 'end_date_time', 'price']
class UploadFileForm(forms.Form): """ An upload file form. """ error_messages = { 'content_type': _("Files of type %(content_type)s are not supported"), 'no_file': _("No file was provided") } supported_filetypes = ['docx', 'pdf', 'txt', 'epub'] file = forms.FileField( label='File input', help_text="Choose a file you'd like to have rated.", required=False, validators=[ FileExtensionValidator(allowed_extensions=supported_filetypes) ], widget=forms.FileInput(attrs={ 'class': 'form-control-file', 'aria-describedby': "fileHelp" })) def __init__(self, *args, **kwargs): """ Initialize the website search form. :param args: :param kwargs: """ super().__init__(*args, **kwargs) self.title = '' def _post_clean(self): """ Clean the website search form. :return: None. """ super()._post_clean() if self.cleaned_data.get("file") is None: self.no_file_error() else: # Set title field self.title = self.cleaned_data.get('file').name def unknown_filetype_error(self): """ Add an unknown_filetype error to the file field. :return: None. """ self.add_error('file', self.error_messages['content_type'], 'content_type') def no_file_error(self): """ Add a no file error to the file field if no file was given. :return: None. """ self.add_error('file', self.error_messages['no_file']) def get_title(self): """ Returns the default value associated with the title of an uploaded file. :return: A string, the name of the uploaded file. """ return self.title def get_creator(self): """ Returns the default value associated with the creator of an uploaded file. :return: A string, the default value associated with the creator of an uploaded file. """ return ''
class TagImportForm(forms.Form): csv_file = forms.FileField(widget=forms.FileInput( attrs={'accept': '.csv'})) clear_existing_tags = forms.BooleanField(label="Clear existing tags", required=False, initial=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def save(self, commit=True): csv_file = self.cleaned_data['csv_file'] clear_existing_tags = self.cleaned_data['clear_existing_tags'] f = TextIOWrapper( csv_file.file, encoding=csv_file.charset if csv_file.charset else 'utf-8') records = csv.DictReader(f) import_errors = False import_success = False count = 0 count_imported = 0 count_notfound = 0 if records: # the first row is the tags for row in records: count += 1 topic = row.get('topic') if not topic: topic = row.get('__topic') entities = Entity.objects.filter(topic=topic) if entities: for entity in entities: if clear_existing_tags: entity.remove_all_tags(commit=False) for tag in row.keys(): if tag != 'topic' and not tag.startswith('__'): value = row.get(tag) # check tag Kind if value: try: tag_object = Tag.objects.get(tag=tag) except Tag.DoesNotExist: logging.error( "Cannot get tag {}".format(tag)) else: if tag_object.kind == 'Marker': entity.add_tag(tag, value=None, commit=False) else: entity.add_tag(tag, value=value, commit=False) entity.save() count_imported += 1 else: count_notfound += 1 else: import_errors = 'Cannot parse source file' if count: if count_imported: t = "row" if count_imported == 1 else "rows" import_success = "Imported {count} {t} successfully. ".format( count=count_imported, t=t) else: import_success = "" if count_notfound: t = "row" if count_notfound == 1 else "rows" import_success += "{count} {t} from your CSV could not be found.".format( count=count_notfound, t=t) else: import_errors = 'There is no any data row in the source file' result = {} if import_errors: result['import_errors'] = import_errors elif import_success: result['import_success'] = import_success return result