class ApplicationForm(ModelFormWithKeywords): title = forms.CharField(required=True, label=_("Title"), max_length=300, widget=forms.Textarea(attrs={ 'style': 'width: 99%', 'rows': 2 })) slug = forms.CharField(required=False) notes = forms.CharField(widget=CKEditorUploadingWidget, required=True, label=_("Notes")) notes_en = forms.CharField(widget=CKEditorUploadingWidget, required=False, label=_("Notes") + " (EN)") datasets = forms.ModelMultipleChoiceField( queryset=Dataset.objects.filter(status=STATUS_CHOICES[0][0]), required=False, widget=FilteredSelectMultiple(_('datasets'), False), label=_("Dataset")) external_datasets = JSONField(label=_('External datasets'), widget=ExternalDatasetsWidget(), required=False) class Meta: model = Application fields = [ 'title', 'slug', 'notes', 'author', 'external_datasets', 'url', 'image', 'illustrative_graphics', 'illustrative_graphics_alt', 'main_page_position', 'status', 'datasets', 'tags' ]
class Job(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) url = models.URLField() method = models.CharField(max_length=16, default='get') data = JSONField() status = models.SmallIntegerField(default=0) referrer = models.URLField() response_header = JSONField() response_content = models.BinaryField(null=True) traceback = models.TextField(default='') STATUS_WAITING = 0 STATUS_RUNNING = 1 STATUS_FAILED = 2 STATUS_OK = 200 def __unicode__(self): return 'Job %s' % self.id
class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification.")) customfields = JSONField(label=_("Extra info"), required=False, widget=JsonPairUserInputs( val_attrs={'size': 35}, key_attrs={'class': 'large'})) organizations = forms.ModelMultipleChoiceField( queryset=Organization.objects.all(), required=False, widget=FilteredSelectMultiple('organizations', False), label=_("Organizations")) class Meta: model = User fields = [ 'email', 'customfields', 'fullname', 'is_staff', 'is_superuser', 'state', 'organizations' ] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): super(UserCreationForm, self).save(commit=False) self.instance.set_password(self.cleaned_data["password1"]) if commit: self.instance.save() if self.instance.pk: self.instance.organizations.set(self.cleaned_data['organizations']) return self.instance
class UserChangeForm(forms.ModelForm): password = auth_forms.ReadOnlyPasswordHashField( label=_("Password"), help_text=_("Raw passwords are not stored, so there is no way to see " "this user's password, but you can change the password " "using <a href=\"../password/\">this form</a>.")) customfields = JSONField(label=_("Extra info"), required=False, widget=JsonPairUserInputs( val_attrs={'size': 35}, key_attrs={'class': 'large'})) organizations = forms.ModelMultipleChoiceField( queryset=Organization.objects.all(), required=False, widget=FilteredSelectMultiple(_('institutions'), False), label=_("Institution")) class Meta: model = User fields = '__all__' def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') if self.instance.pk: self.fields[ 'organizations'].initial = self.instance.organizations.all() def clean_password(self): return self.initial["password"] def save(self, commit=True): super(UserChangeForm, self).save(commit=False) if commit: self.instance.save() if self.instance.pk: self.instance.organizations.set(self.cleaned_data['organizations']) return self.instance
def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) self.integration_config_fields = [] self.integration_form = None self.fields = copy.deepcopy(self.base_fields) use_config_class = False if self.instance.pk: try: use_config_class = self.instance.application.has_config_class except Registry.IntegrationUnavailableException: pass config = self.instance.get_config() # An empty string means default api_client_name. Since django treats null and # blank equally any null values are rendered as default api_client_name. To get # around this we add an option to be used as null. self.fields["api_client_name"].choices = [("-", "-")] + self.fields[ "api_client_name" ].choices if self.initial.get("api_client_name") is None: self.initial["api_client_name"] = "-" if use_config_class: integration_class = self.instance.application.get_integration_instance() self.integration_form = integration_class.config_form_class for name, field in self.integration_form.base_fields.items(): self.integration_config_fields.append(name) self.fields[name] = field self.initial[name] = config.get(name, field.initial) else: # Application has no integration # Render config field self.fields["config"] = JSONField(required=False) self.initial["config"] = config
class RouterForm(BootstrapMixin, forms.ModelForm): netbox_device_id = forms.IntegerField(label="NetBox Device", initial=0) platform = forms.ChoiceField(required=False, choices=add_blank_choice(Platform.choices), widget=StaticSelect) configuration_template = DynamicModelChoiceField( required=False, queryset=Configuration.objects.all(), label="Configuration", help_text="Template used to generate device configuration", ) napalm_username = forms.CharField(required=False, label="Username") napalm_password = PasswordField(required=False, render_value=True, label="Password") napalm_timeout = forms.IntegerField( required=False, label="Timeout", help_text="The maximum time to wait for a connection in seconds", ) napalm_args = JSONField( required=False, label="Optional Arguments", help_text= "See NAPALM's <a href='http://napalm.readthedocs.io/en/latest/support/#optional-arguments'>documentation</a> for a complete list of optional arguments", widget=SmallTextarea, ) comments = CommentField() tags = TagField(required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if settings.NETBOX_API: self.fields["netbox_device_id"] = forms.ChoiceField( label="NetBox Device", choices=[(0, "--------")] + [(device.id, device.display_name) for device in NetBox().get_devices()], widget=StaticSelect, ) self.fields["netbox_device_id"].widget.attrs["class"] = " ".join([ self.fields["netbox_device_id"].widget.attrs.get("class", ""), "form-control", ]).strip() else: self.fields["netbox_device_id"].widget = forms.HiddenInput() class Meta: model = Router fields = ( "netbox_device_id", "use_netbox", "name", "hostname", "platform", "encrypt_passwords", "configuration_template", "napalm_username", "napalm_password", "napalm_timeout", "napalm_args", "comments", "tags", ) labels = {"use_netbox": "Use NetBox"} help_texts = { "hostname": "Router hostname (must be resolvable) or IP address" }
class DatasetForm(forms.ModelForm): title = forms.CharField(widget=forms.Textarea( attrs={ 'placeholder': _('e.g. the name of the data set'), 'style': 'width: 99%', 'rows': 1 }), label=_("Title")) slug = forms.CharField(label="URL", widget=forms.TextInput(attrs={'size': 85}), required=False) notes = forms.CharField(widget=CKEditorWidget( attrs={ 'placeholder': _("Some information about the data being added"), 'cols': 80, 'rows': 10 }), required=False, label=_('Notes')) update_frequency = forms.ChoiceField(choices=FREQUENCY, label=_("Update frequency")) url = forms.URLField(required=False, widget=forms.TextInput(attrs={'size': 85}), label=_("Source")) customfields = JSONField(label=_("Customfields"), widget=JsonPairDatasetInputs( val_attrs={'size': 35}, key_attrs={'class': 'large'}), required=False) license_condition_source = forms.BooleanField(label=_( "The recipient should inform about the date, " "time of completion and obtaining information from the obliged entity" ), required=False) license_condition_modification = forms.BooleanField(label=_( "The recipient should inform about the processing of the information when it modifies it" ), required=False) license_condition_responsibilities = forms.CharField(label=_( "The scope of the provider's responsibility for the information provided" ), widget=CKEditorWidget, required=False) license_condition_db_or_copyrighted = forms.CharField(label=_( "Conditions for using public information that meets the characteristics of the work or constitute " "a database (Article 13 paragraph 2 of the Act on the re-use of public sector information)" ), widget=CKEditorWidget, required=False) class Meta: model = Dataset fields = [ 'title', 'slug', 'category', 'notes', 'tags', 'organization', 'url', 'update_frequency', 'customfields', 'license_condition_db_or_copyrighted', 'license_condition_modification', 'license_condition_responsibilities', 'license_condition_source', 'status', ] def clean_slug(self): self.cleaned_data['slug'] = get_unique_slug(self.auto_id, self.data['slug'], Dataset.raw)
class DatasetForm(forms.ModelForm): title = forms.CharField( widget=forms.Textarea( attrs={ 'placeholder': _('e.g. the name of the data set'), 'style': 'width: 99%', 'rows': 1 }), label=_("Title"), max_length=300, ) slug = forms.CharField(label="URL", widget=forms.TextInput(attrs={'size': 85}), required=False) notes = forms.CharField(widget=CKEditorWidget( attrs={ 'placeholder': _("Some information about the data being added"), 'cols': 80, 'rows': 10 }), required=True, label=_('Notes')) notes_en = forms.CharField(widget=CKEditorWidget( attrs={ 'placeholder': _("Some information about the data being added"), 'cols': 80, 'rows': 10 }), required=False, label=_('Notes') + " (EN)") update_frequency = forms.ChoiceField(choices=UPDATE_FREQUENCY, label=_("Update frequency")) url = forms.URLField(required=False, widget=forms.TextInput(attrs={'size': 85}), label=_("Source"), max_length=1000) customfields = JSONField(label=_("Customfields"), widget=JsonPairDatasetInputs( val_attrs={'size': 35}, key_attrs={'class': 'large'}), required=False) license_condition_source = forms.BooleanField(label=_( "The recipient should inform about the date, " "time of completion and obtaining information from the obliged entity" ), required=False) license_condition_modification = forms.BooleanField(label=_( "The recipient should inform about the processing of the information when it modifies it" ), required=False) license_condition_responsibilities = forms.CharField(label=_( "The scope of the provider's responsibility for the information provided" ), widget=CKEditorWidget, required=False) license_condition_db_or_copyrighted = forms.CharField(label=_( "Conditions for using public information that meets the characteristics of the work or constitute " "a database (Article 13 paragraph 2 of the Act on the re-use of public sector information)" ), widget=CKEditorWidget, required=False) status = forms.ChoiceField( choices=STATUS_CHOICES, help_text=_( "If you select a draft, the status of all published resources belonging " "to that set will be changed to a draft")) class Meta: model = Dataset fields = [ 'title', 'slug', 'category', 'notes', 'tags', 'organization', 'url', 'update_frequency', 'customfields', 'license_condition_db_or_copyrighted', 'license_condition_modification', 'license_condition_responsibilities', 'license_condition_source', 'status', ] labels = { 'created': _("Availability date"), 'modified': _("Modification date"), 'verified': _("Update date"), } # def clean_slug(self): # self.cleaned_data['slug'] = get_unique_slug(self.auto_id, self.data['slug'], Dataset.raw) # return self.cleaned_data['slug'] def clean_status(self): if self.instance.id: organization = self.instance.organization else: organization = self.cleaned_data.get('organization') if organization and organization.status == 'draft': if self.cleaned_data['status'] == 'published': error_message = _( "You can't publish this dataset, because his organization has the status of a draft " "Please set status to draft or set status to publish for organization: " ) error_message += "<a href='{}'>{}</a>".format( reverse('admin:organizations_organization_change', args=[organization.id]), organization.title) raise forms.ValidationError(mark_safe(error_message)) return self.cleaned_data['status']
class ShowcaseForm(ModelFormWithKeywords): title = forms.CharField(required=True, label=_('Title'), max_length=300, widget=forms.Textarea(attrs={ 'style': 'width: 99%', 'rows': 2 })) slug = forms.CharField(required=False) notes = forms.CharField(widget=CKEditorUploadingWidget, required=True, label=_('Notes')) notes_en = forms.CharField(widget=CKEditorUploadingWidget, required=False, label=_('Notes') + ' (EN)') datasets = forms.ModelMultipleChoiceField( queryset=Dataset.objects.filter(status=STATUS_CHOICES[0][0]), required=False, widget=FilteredSelectMultiple(_('datasets'), False), label=_('Dataset')) external_datasets = JSONField(label=_('External datasets'), widget=ExternalDatasetsWidget(), required=False) class Meta: model = Showcase fields = [ 'category', 'title', 'slug', 'is_mobile_app', 'mobile_apple_url', 'mobile_google_url', 'is_desktop_app', 'desktop_windows_url', 'desktop_linux_url', 'desktop_macos_url', 'license_type', 'notes', 'author', 'external_datasets', 'url', 'image', 'illustrative_graphics', 'illustrative_graphics_alt', 'main_page_position', 'status', 'datasets', 'tags' ] labels = { 'desktop_linux_url': get_link_label('ic-linux.svg', 'Linux'), 'desktop_macos_url': get_link_label('ic-apple.svg', 'MacOS'), 'desktop_windows_url': get_link_label('ic-windows.svg', 'Windows'), 'mobile_apple_url': get_link_label('ic-apple.svg', 'iOS'), 'mobile_google_url': get_link_label('ic-android.svg', 'Android'), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in [ 'mobile_apple_url', 'mobile_google_url', 'desktop_windows_url', 'desktop_linux_url', 'desktop_macos_url' ]: if name in self.fields: css_class = self.fields[name].widget.attrs.get('class', '') css_class += ' span12' self.fields[name].widget.attrs.update({ 'placeholder': 'https://', 'class': css_class }) def clean(self): data = super().clean() category = data.get('category') is_mobile_app = data.get('is_mobile_app', False) is_desktop_app = data.get('is_desktop_app', False) license_type = data.get('license_type') mobile_apple_url = data.get('mobile_apple_url') mobile_google_url = data.get('mobile_google_url') desktop_linux_url = data.get('desktop_linux_url') desktop_macos_url = data.get('desktop_macos_url') desktop_windows_url = data.get('desktop_windows_url') if category in ('app', 'www'): if not license_type: self.add_error('license_type', _('This field is required!')) else: data['license_type'] = '' if is_mobile_app and not any([mobile_apple_url, mobile_google_url]): self.add_error( None, _('At least one url for mobile app (iOS, Android) is required!' )) if is_desktop_app and not any( [desktop_linux_url, desktop_macos_url, desktop_windows_url]): self.add_error( None, _('At least one url for desktop app (Windows, Linux, MacOS) is required!' )) return data
class ChangeResourceForm(ResourceForm): tabular_data_schema = JSONField(widget=ResourceDataSchemaWidget(), required=False) data_rules = JSONField(widget=ResourceDataRulesWidget(), required=False) maps_and_plots = MapsJSONField(widget=ResourceMapsAndPlotsWidget(), required=False) def __init__(self, *args, **kwargs): if 'instance' in kwargs: kwargs['initial'] = { 'data_rules': kwargs['instance'].tabular_data_schema, 'maps_and_plots': kwargs['instance'].tabular_data_schema, } super(ChangeResourceForm, self).__init__(*args, **kwargs) if hasattr(self, 'instance'): self.fields['tabular_data_schema'].widget.instance = self.instance self.fields['data_rules'].widget.instance = self.instance self.fields['maps_and_plots'].widget.instance = self.instance if 'regions' in self.fields: self.fields['regions'].choices = self.instance.regions.all( ).values_list('region_id', 'hierarchy_label') def clean_status(self): dataset = self.instance.dataset if self.cleaned_data[ 'status'] == 'published' and dataset.status == 'draft': error_message = _( "You can't set status of this resource to published, because it's dataset is still a draft. " "You should first published that dataset: ") error_message += "<a href='{}'>{}</a>".format( dataset.admin_change_url, dataset.title) raise forms.ValidationError(mark_safe(error_message)) return self.cleaned_data['status'] class Meta: model = Resource exclude = [ "old_resource_type", ] if is_enabled('S40_new_file_model.be'): labels = { 'created': _("Availability date"), 'modified': _("Modification date"), 'verified': _("Update date"), 'is_chart_creation_blocked': _('Do not allow user charts to be created'), 'main_file': _('File'), 'csv_converted_file': _("File as CSV"), 'jsonld_converted_file': _("File as JSON-LD"), 'main_file_info': _('File info'), 'main_file_encoding': _('File encoding') } else: labels = { 'created': _("Availability date"), 'modified': _("Modification date"), 'verified': _("Update date"), 'is_chart_creation_blocked': _('Do not allow user charts to be created') }
class DatasetForm(ModelFormWithKeywords): title = forms.CharField( widget=forms.Textarea( attrs={ 'placeholder': _('e.g. the name of the data set'), 'style': 'width: 99%', 'rows': 2 }), label=_("Title"), max_length=300, ) slug = forms.SlugField(label="Slug", widget=forms.TextInput(attrs={'size': 85}), required=False) notes = forms.CharField( min_length=20, widget=CKEditorWidget( attrs={ 'placeholder': _( "Some information about the data being added"), 'cols': 80, 'rows': 10 }), required=True, label=_('Notes'), validators=[ContainsLetterValidator()], ) notes_en = forms.CharField( min_length=20, widget=CKEditorWidget( attrs={ 'placeholder': _( "Some information about the data being added"), 'cols': 80, 'rows': 10 }), required=False, label=_('Notes') + " (EN)", validators=[ContainsLetterValidator()], ) update_frequency = forms.ChoiceField(choices=UPDATE_FREQUENCY, label=_("Update frequency")) url = forms.URLField(required=False, widget=forms.TextInput(attrs={'size': 85}), label=_("Source"), max_length=1000) customfields = JSONField(label=_("Customfields"), widget=JsonPairDatasetInputs( val_attrs={'size': 35}, key_attrs={'class': 'large'}), required=False) status = forms.ChoiceField( choices=STATUS_CHOICES, help_text=_( "If you select a draft, the status of all published resources belonging " "to that set will be changed to a draft")) if is_enabled('S41_resource_has_high_value_data.be'): has_high_value_data = forms.ChoiceField( disabled=True, initial=False, required=False, label=_('has high value data').capitalize(), help_text= ('Zaznaczając dane dodane w zbiorze danych zostaną określone jako wysokiej wartości. Są to dane, ' 'których ponowne wykorzystanie wiąże się z istotnymi korzyściami dla społeczeństwa, środowiska ' 'i gospodarki'), choices=[(True, _('Yes')), (False, _('No'))], widget=forms.RadioSelect(attrs={'class': 'inline'})) def __init__(self, *args, instance=None, **kwargs): if instance and is_enabled('S41_resource_has_high_value_data.be'): initial = kwargs.get('initial', {}) initial['has_high_value_data'] = instance.has_high_value_data kwargs['initial'] = initial super(DatasetForm, self).__init__(*args, instance=instance, **kwargs) if 'categories' in self.fields and is_enabled( 'S41_dataset_categories_required.be'): self.fields['categories'].required = True try: self.fields['image'].validators.append( validate_dataset_image_file_extension) self.fields['image'].help_text = \ _('Allowed file extensions: jpg, gif, png. For better readability,' ' we recommend .png files with a transparent background') except KeyError: pass if self.fields.get('tags_pl'): self.fields['tags_pl'].required = True if 'update_notification_recipient_email' in self.fields: self.fields['update_notification_recipient_email'].required = True if instance and instance.modified_by and not instance.update_notification_recipient_email: self.initial[ 'update_notification_recipient_email'] = instance.modified_by.email class Meta: model = Dataset widgets = { 'license_condition_source': CheckboxInputWithLabel(label='CC BY 4.0'), 'license_condition_modification': CheckboxInputWithLabel(label='CC BY 4.0'), 'license_condition_responsibilities': CKEditorWidget(config_name='licenses'), 'license_condition_db_or_copyrighted': CKEditorWidget(config_name='licenses'), 'license_chosen': forms.RadioSelect, 'license_condition_personal_data': CKEditorWidget(config_name='licenses'), 'update_notification_frequency': forms.TextInput(attrs={'maxlength': 3}), } fields = [ 'title', 'slug', 'category', 'categories', 'notes', 'tags', 'organization', 'url', 'image', 'update_frequency', 'customfields', 'license_condition_source', 'license_condition_modification', 'license_condition_responsibilities', 'license_condition_db_or_copyrighted', 'license_chosen', 'license_condition_personal_data', 'status', ] help_texts = { 'update_notification_recipient_email': ('Uwaga! Adres email zostanie nadpisany adresem edytora, który będzie modyfikował metadane zbioru.' ), } labels = { 'created': _("Availability date"), 'modified': _("Modification date"), 'verified': _("Update date"), } def clean(self): cleaned_data = super().clean() if cleaned_data.get('license_condition_db_or_copyrighted' ) and not cleaned_data.get('license_chosen'): self.add_error('license_chosen', _('Text area is filled, license must be selected')) return cleaned_data def clean_license_condition_personal_data(self): if self.cleaned_data.get('license_condition_personal_data'): raise forms.ValidationError( _('Chosen conditions for re-use mean that they contain personal data. ' 'Please contact the administrator at [email protected].')) return self.cleaned_data['license_condition_personal_data'] def clean_status(self): if self.instance.id: organization = self.instance.organization else: organization = self.cleaned_data.get('organization') if organization and organization.status == 'draft': if self.cleaned_data['status'] == 'published': error_message = _( "You can't publish this dataset, because his organization has the status of a draft " "Please set status to draft or set status to publish for organization: " ) error_message += "<a href='{}'>{}</a>".format( reverse('admin:organizations_organization_change', args=[organization.id]), organization.title) raise forms.ValidationError(mark_safe(error_message)) return self.cleaned_data['status']