class PostModelForm(CustomFileFormMixin, forms.ModelForm): """Render a Post model form.""" image = UploadedFileField(label=_('Світлина'), required=False) image_pl = UploadedFileField(label=_('Світлина польською'), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.fields['image'].initial = self.instance.image if self.instance: self.fields['image_pl'].initial = self.instance.image_pl self.fields['pub_date'].input_formats = ['%d-%m-%Y %H:%M'] if not self.instance.pub_date: self.fields['pub_date'].initial = timezone.now().strftime( '%d-%m-%Y %H:%M') class Meta: model = Post fields = ('title', 'body', 'short_descr', 'title_pl', 'body_pl', 'short_descr_pl', 'pub_date', 'slug') widgets = { 'short_descr': forms.Textarea(attrs={ 'cols': 80, 'rows': 2 }), 'short_descr_pl': forms.Textarea(attrs={ 'cols': 80, 'rows': 2 }), 'body': TinyMCE(attrs={ 'cols': 80, 'rows': 20 }), 'body_pl': TinyMCE(attrs={ 'cols': 80, 'rows': 20 }), } def save(self, commit=True): instance = super().save(commit=False) image = self.cleaned_data['image'] image_pl = self.cleaned_data['image_pl'] instance.image = image instance.image_pl = image_pl if commit: instance.save() self.delete_temporary_files() return instance
class DumpForm(FileFormMixin, forms.ModelForm): upload = UploadedFileField() password = forms.CharField(required=False) class Meta: model = Dump fields = ("upload", "name", "operating_system", "password", "color")
class SymbolForm(FileFormMixin, forms.ModelForm): METHODS = ( (0, "Suggested path"), (1, "Upload linux packages"), (2, "Upload symbol"), ) method = forms.IntegerField(label="Method", widget=forms.Select(choices=METHODS)) path = SimpleArrayField(forms.CharField(required=False)) packages = MultipleUploadedFileField(required=False) symbol = UploadedFileField(required=False) def __init__(self, *args, **kwargs): super(SymbolForm, self).__init__(*args, **kwargs) self.fields["banner"].widget.attrs["readonly"] = True class Meta: model = Dump fields = ( "index", "operating_system", "banner", "method", "path", "packages", "symbol", ) widgets = { "index": forms.HiddenInput(), "operating_system": forms.HiddenInput(), }
class PostForm(FileFormMixin, betterforms.BetterForm): name = forms.CharField(label="name", max_length=200) body = forms.CharField(label="body", widget=TinyMCE(attrs={ 'cols': 80, 'rows': 30 }), required=False) pub_date = forms.DateTimeField(label="publication date", widget=DateTimeWidget(usel10n=True, bootstrap_version=3), initial=timezone.now) image = UploadedFileField(label="image", required=False) form_id = forms.CharField(widget=forms.HiddenInput(), required=False) upload_url = forms.CharField(widget=forms.HiddenInput(), required=False) delete_url = forms.CharField(widget=forms.HiddenInput(), required=False) object_id = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: fieldsets = [ ('main', { 'fields': ['name', 'language', 'pub_date'], 'legend': 'main', }), ('text-area', { 'fields': ['body'], 'legend': 'text-area' }), ('images', { 'fields': ['image'] + ['form_id', 'upload_url', 'delete_url'], 'legend': 'images' }), ]
class ExampleForm(BaseForm): input_file = UploadedFileField() def save(self): Example.objects.create(title=self.cleaned_data['title'], input_file=self.cleaned_data['input_file']) self.delete_temporary_files()
class PlaceholderS3ExampleForm(BaseForm): prefix = "example" input_file = MultipleUploadedFileField() other_input_file = UploadedFileField() s3_upload_dir = "s3_placeholder_example" def save(self): self.delete_temporary_files()
class ExampleForm(BaseForm): prefix = "example" input_file = UploadedFileField() def save(self): input_file = self.cleaned_data["input_file"] try: Example.objects.create(title=self.cleaned_data["title"], input_file=input_file) finally: input_file.close() self.delete_temporary_files()
class UserUpdateForm(FileFormMixin, betterforms.BetterForm): username = forms.CharField(required=False) email = forms.EmailField(required=False) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) old_password = forms.CharField(required=False, label="Old Password", widget=forms.PasswordInput()) password1 = forms.CharField(required=False, label="New Password", widget=forms.PasswordInput()) password2 = forms.CharField(required=False, label="Confirm New Password", widget=forms.PasswordInput()) country = forms.CharField(required=False) city = forms.CharField(required=False) organization = forms.CharField(required=False, label="Research oragnization (University)") avatar = UploadedFileField(label=_("Profile image"), required=False) form_id = forms.CharField(widget=forms.HiddenInput(), required=False) upload_url = forms.CharField(widget=forms.HiddenInput(), required=False) delete_url = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: fieldsets = [('1', { 'description': _('Main Info'), 'legend': 'main_info', 'fields': ['username', 'email', 'first_name', 'last_name'], }), ('2', { 'description': _('Password management'), 'legend': 'update_password', 'fields': ['old_password', 'password1', 'password2'], }), ('3', { 'description': _('User Profile'), 'legend': 'user_profile', 'fields': [ 'country', 'city', 'organization', 'avatar', 'form_id', 'upload_url', 'delete_url' ], })]
class PlaceholderExampleForm(BaseForm): prefix = "example" input_file = MultipleUploadedFileField() other_input_file = UploadedFileField() def save(self): example = Example2.objects.create(title=self.cleaned_data["title"]) for f in self.cleaned_data["input_file"]: if f.is_placeholder: continue try: ExampleFile.objects.create(example=example, input_file=f) finally: f.close() self.delete_temporary_files()
class MacroGroupForm(FileFormMixin, G3WFormMixin, ModelForm): """MacroGroup form.""" logo_img = UploadedFileField() def __init__(self, *args, **kwargs): super(MacroGroupForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('General data'))), css_class='box-header with-border' ), Div( 'title', Field('description', css_class='wys5', style="width:100%;"), 'logo_img', HTML( """<img {% if not form.logo_img.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.logo_img.value }}">""", ), 'form_id', 'upload_url', 'delete_url', css_class='box-body' ), css_class='box box-success' ), css_class='col-md-12' ), css_class='row' ) ) class Meta: model = MacroGroup fields = '__all__'
class TeacherModelForm(CustomFileFormMixin, forms.ModelForm): """Render a Post model form.""" image = UploadedFileField(label=_('Світлина'), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.fields['image'].initial = self.instance.image self.fields['pub_date'].input_formats = ['%d-%m-%Y %H:%M'] if not self.instance.pub_date: self.fields['pub_date'].initial = timezone.now().strftime( '%d-%m-%Y %H:%M') class Meta: model = Teacher fields = ('first_name', 'last_name', 'information', 'first_name_pl', 'last_name_pl', 'information_pl', 'slug', 'pub_date') widgets = { 'information': forms.Textarea(attrs={ 'cols': 80, 'rows': 3 }), 'information_pl': forms.Textarea(attrs={ 'cols': 80, 'rows': 3 }), } def save(self, commit=True): instance = super().save(commit=False) image = self.cleaned_data['image'] instance.image = image if commit: instance.save() self.delete_temporary_files() return instance
def __init__(self, *args, **kwargs): super(NewSiteForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(max_length=128, label=_('Name')) self.fields['undefined'] = forms.BooleanField( required=False, label=_('Dating is undefined')) self.fields['literature'] = forms.CharField(required=False, widget=forms.Textarea, max_length=2048, label=_('Literature')) self.create_filter_fields() # create image fields for i, choice in ImageType.choices: field = None # limit site profile picture to one if i == ImageType.general: field = UploadedFileField(required=False, label=_(choice)) else: field = MultipleUploadedFileField(required=False, label=_(choice)) self.fields[choice.lower()] = field
class UserUpdateForm(FileFormMixin, betterforms.BetterForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) country = forms.CharField(required=False) city = forms.CharField(required=False) birthday = forms.DateField(required=False, initial=timezone.now, widget=DateWidget(usel10n=True, bootstrap_version=3, options={ 'startView': 4, })) avatar = UploadedFileField(label="Profile image", required=False) form_id = forms.CharField(widget=forms.HiddenInput(), required=False) upload_url = forms.CharField(widget=forms.HiddenInput(), required=False) delete_url = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: fieldsets = [('1', { 'description': 'User Info', 'legend': 'main_info', 'fields': ['username', 'email', 'first_name', 'last_name'], }), ('2', { 'description': 'User Info', 'legend': 'user_profile', 'fields': [ 'country', 'city', 'birthday', 'avatar', 'form_id', 'upload_url', 'delete_url' ], })]
class SpeakerForm(FileFormMixin, forms.models.ModelForm): uploaded_image = UploadedFileField(label=_("Speaker portrait")) class Meta: model = Speaker fields = ["shortbio", "videopermission", "shirt_size"] widgets = { 'shortbio': forms.Textarea(attrs={'rows': 3}), } def __init__(self, *args, **kwargs): super(SpeakerForm, self).__init__(*args, **kwargs) def save(self, commit=True): speaker = self.instance assert hasattr(self, 'cleaned_data') speaker.portrait = self.cleaned_data.get('uploaded_image') result = super(SpeakerForm, self).save(commit) if commit: try: self.delete_temporary_files() except: pass return result
class QdjangoProjectForm(TranslationModelForm, QdjangoProjectFormMixin, G3WFormMixin, G3WGroupFormMixin, G3WGroupBaseLayerFormMixin, G3WRequestFormMixin, G3WACLForm, FileFormMixin, forms.ModelForm): qgis_file = UploadedFileField(required=True) thumbnail = UploadedFileField(required=False) url_alias = forms.CharField( required=False, label=_('URL alias'), help_text=_( 'You can set a human readable URL for the map. Only alphanumeric characters, not white space or ' 'special characters')) # QGIS Authentication extra fields authentication_id = forms.CharField( label=_("QGIS Authentication ID"), required=False, max_length=7, validators=[RegexValidator(r'[A-z0-9]{7}')], help_text=_('7 alphanumeric ASCII chars'), widget=forms.HiddenInput()) authentication_username = forms.CharField(label=_("Username"), required=False) authentication_password = forms.CharField(label=_("Password"), required=False, widget=forms.PasswordInput()) def __init__(self, *args, **kwargs): if 'instance' in kwargs and hasattr(kwargs['instance'], 'url_alias'): kwargs['initial']['url_alias'] = kwargs['instance'].url_alias super().__init__(*args, **kwargs) # rebuild toc_tab_default by baselayers saved into part group base_layers = self.group.baselayers.count() if not base_layers: nc = list(Project.CLIENT_TOC_TABS) del (nc[1]) self.fields['toc_tab_default'].choices = nc # Check for authcfg errors if self.has_error('qgis_file'): for err in self.errors['qgis_file']: if 'authcfg' in err: try: authcfg = re.findall(r'authcfg=(\w{7})', err)[0] if QgisAuth.objects.filter(id=authcfg).count() == 0: kwargs['initial']['authentication_id'] = authcfg self.fields['authentication_id'].initial = authcfg data = self.data.copy() data['authentication_id'] = authcfg self.data = data else: # This authcfg already exists but the error might be not related if not '__all__' in self.errors: self.errors['__all__'] = [] self.errors['__all__'].append( mark_safe( _('Warning: an invalid layer is using an existing authentication configuration ({authentication_id}). Ask an administrator to check if the configuration is correct by browinsg the URL<a target=_new href="{admin_url}">{admin_url}</a>' ).format( authentication_id=authcfg, admin_url=reverse( 'admin:qdjango_qgisauth_change', args=(authcfg, ))))) except: pass self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='ion ion-map'></i> {}</h3>". format(_('Qgis Project'))), css_class='box-header with-border'), Div( 'qgis_file', 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), crispyBoxACL(self), crispyBoxBaseLayer(self), css_class='row'), Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Description data'))), css_class='box-header with-border'), Div( 'title_ur', Field('description', css_class='wys5'), 'thumbnail', HTML( """<img {% if not form.thumbnail.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.thumbnail.value }}">""", ), 'url_alias', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), Div(Div(Div(HTML( "<h3 class='box-title'><i class='ion ion-gear'></i> {}</h3>" .format(_('Options and actions'))), css_class='box-header with-border'), Div( 'use_map_extent_as_init_extent', 'toc_tab_default', 'toc_layers_init_status', 'toc_themes_init_status', 'legend_position', 'autozoom_query', 'feature_count_wms', 'multilayer_query', 'multilayer_querybybbox', 'multilayer_querybypolygon', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), css_class='row'), ) if self.fields['authentication_id'].initial: auth_box = Div(Div(Div(HTML( """<h3 class='box-title'><i class='fa fa-lock'></i> {}</h3> <p>The error in the project suggests that one or more layers require authentication. You can add the required credentials now. Credentials will be encrypted and added to the QGIS Authentication DB.</p> <p><strong>Authentication ID: {}</strong></p>""" .format(_('QGIS Authentication'), self.fields['authentication_id'].initial)), css_class='box-header with-border'), Div( 'authentication_id', 'authentication_username', 'authentication_password', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6') self.helper.layout.fields.insert(1, auth_box) class Meta: model = Project fields = ( 'qgis_file', 'description', 'thumbnail', 'baselayer', 'feature_count_wms', 'toc_tab_default', 'toc_layers_init_status', 'toc_themes_init_status', 'legend_position', 'autozoom_query', 'multilayer_query', 'multilayer_querybybbox', 'multilayer_querybypolygon', 'use_map_extent_as_init_extent', 'context_base_legend', 'title_ur', ) def _setEditorUserQueryset(self): """ Set query set for editors chosen fields :return: None """ # add filter by group permissions editor_group = get_users_for_object(self.group, 'change_group', [G3W_EDITOR1]) editor2_group = get_users_for_object(self.group, 'add_project_to_group', [G3W_EDITOR2]) self.fields['editor_user'].queryset = get_objects_for_user(self.request.user, 'auth.change_user', User) \ .filter(pk__in=[e.pk for e in editor_group], groups__name__in=self.editor1_groups) self.fields['editor2_user'].queryset = get_objects_for_user(self.request.user, 'auth.change_user', User) \ .filter(pk__in=[e.pk for e in editor2_group], groups__name__in=self.editor2_groups) def _setViewerUserQueryset(self, **kwargs): """ Set queryset for viewers chosen fields Take Viewers level 1 from Group :return: None """ # get viewers from groups viewers = get_viewers_for_object(self.group, self.request.user, 'view_group') # get queryset self.fields['viewer_users'].queryset = User.objects.filter( groups__name__in=self.viewer_groups, pk__in=[v.pk for v in viewers]) def _set_user_groups_queryset(self): """ Set query set for viewer user groups chosen fields Take Viewer User Groups from Group :return: None """ super(QdjangoProjectForm, self)._set_user_groups_queryset() editor_user_groups = get_user_groups_for_object( self.group, self.request.user, 'view_group', 'editor') self.fields['editor_user_groups'].queryset = AuthGroup.objects.filter( pk__in=[v.pk for v in editor_user_groups]) viewer_user_groups = get_user_groups_for_object( self.group, self.request.user, 'view_group', 'viewer') self.fields['viewer_user_groups'].queryset = AuthGroup.objects.filter( pk__in=[v.pk for v in viewer_user_groups]) def save(self, commit=True): self._ACLPolicy() self._save_url_alias() # add permission to Editor level 1 and 2 if current user is Editor level 1 or 2 if userHasGroups(self.request.user, [G3W_EDITOR1, G3W_EDITOR2]): self.instance.addPermissionsToEditor(self.request.user) # give permission to Editor level 1 of group id user is Editor level 2 if userHasGroups(self.request.user, [G3W_EDITOR2]): # give permission to user groups of map group user_editor_groups = get_groups_for_object( self.instance.group, 'view_group', 'editor') self.instance.add_permissions_to_editor_user_groups( [uge.pk for uge in user_editor_groups]) editor_users = get_users_for_object(self.instance.group, 'view_group', [G3W_EDITOR1, G3W_EDITOR2]) for eu in editor_users: self.instance.addPermissionsToEditor(eu)
class PluginCreateAdminForm(FileFormMixin, forms.ModelForm): plugin = UploadedFileField(required=True) class Meta: model = Plugin fields = [ "plugin", "operating_system", "disabled", "local_dump", "vt_check", "clamav_check", "regipy_check", ] def save(self, commit=True): plugin = self.cleaned_data["plugin"] bash_script = None reqs_script = False py_name = None plugin_folder = Path(settings.VOLATILITY_PLUGIN_PATH) tmp_folder = plugin_folder / str(uuid.uuid4()) os.mkdir(tmp_folder) with zipfile.ZipFile(plugin.file.path, "r") as f: for name in f.namelist(): if name.endswith(".sh"): bash_script = f.read(name) elif name.lower() == "requirements.txt": reqs_script = True with open(tmp_folder / "requirements.txt", "wb") as reqs: reqs.write(f.read(name)) elif name.endswith(".py"): with open(plugin_folder / name, "wb") as reqs: reqs.write(f.read(name)) py_name = Path(name).stem if bash_script: os.system(shlex.quote("apt update")) os.system(shlex.quote(bash_script)) if reqs_script: os.system( shlex.quote( "pip install -r {}/requirements.txt".format(tmp_folder))) _ = contexts.Context() _ = framework.import_files(volatility3.plugins, True) available_plugins = framework.list_plugins() for plugin in available_plugins: if plugin.startswith("custom.{}".format(py_name)): self.cleaned_data["name"] = plugin def install(bash_script, reqs_script, tmp_folder): if bash_script: os.system(shlex.quote("apt update")) os.system(shlex.quote(bash_script)) if reqs_script: os.system( shlex.quote("pip install -r {}/requirements.txt".format( tmp_folder))) os.system(shlex.quote("rm -rf {}".format(tmp_folder))) dask_client = get_client(address="tcp://scheduler:8786") dask_client.run(install, bash_script, reqs_script, tmp_folder) plugin = super(PluginCreateAdminForm, self).save(commit=commit) for available_plugin in available_plugins: if available_plugin.startswith("custom.{}".format(py_name)): plugin.name = available_plugin plugin.save() return plugin
class DumpForm(FileFormMixin, forms.ModelForm): upload = UploadedFileField() class Meta: model = Dump fields = ("upload", "name", "operating_system", "color")
class GroupForm(FileFormMixin, G3WFormMixin, G3WRequestFormMixin, G3WACLForm, ModelForm): """Group form.""" header_logo_img = UploadedFileField() def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) # add MacroGroups by users self.fields['macrogroups'].queryset = get_objects_for_user(self.request.user, 'view_macrogroup', MacroGroup) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('General data'))), css_class='box-header with-border' ), Div( 'name', 'title', Field('description', css_class='wys5', style="width:100%;"), Field('lang', css_class='select2', style="width:100%;"), css_class='box-body', ), css_class='box box-success' ), css_class='col-md-6' ), crispyBoxACL(self), crispyBoxMacroGroups(self), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-globe'></i> {}</h3>".format(_('GEO data'))), css_class='box-header with-border' ), Div( Div( Div( Field('srid', css_class='select2', style="width:100%;"), css_class='col-md-12' ), css_class='row' ), css_class='box-body' ), css_class='box box-danger' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-map'></i> {}</h3>".format(_('Base Layers and Map default features'))), Div( HTML("<button class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"), css_class='box-tools', ), css_class='box-header with-border' ), Div( Field('mapcontrols', **{'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;'}), Field('baselayers', **{'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;'}), AppendedText('background_color', '<i></i>', css_class='colorpicker'), css_class='box-body' ), css_class='box box-danger' ), css_class='col-md-6' ), css_class='row' ), Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file-image-o'></i> {}</h3>".format(_('Logo/Picture'))), css_class='box-header with-border' ), Div( Div( 'header_logo_img', HTML("""<img {% if not form.header_logo_img.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.header_logo_img.value }}">""", ), 'form_id', 'upload_url', 'delete_url', css_class='col-md-12' ), Div( #AppendedText('header_logo_height','px'), 'header_logo_link', css_class='col-md-12' ), css_class='box-body' ), css_class='box box-primary' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-copyright'></i> {}</h3>".format(_('Copyright'))), Div( HTML("<button class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"), css_class='box-tools', ), css_class='box-header with-border' ), Div( Field('header_terms_of_use_text',css_class='wys5'), 'header_terms_of_use_link', css_class='box-body' ), css_class='box box-default {}'.format(self.checkEmptyInitialsData('header_terms_of_use_text','header_terms_of_use_link')) ), css_class='col-md-6' ), css_class='row' ) ) class Meta: model = Group fields = '__all__' def save(self, commit=True): super(GroupForm, self).save() self._ACLPolicy() # add permission to editor1 if current user is editor1 if userHasGroups(self.request.user, [G3W_EDITOR1]): self.instance.addPermissionsToEditor(self.request.user)
class MacroGroupForm(FileFormMixin, G3WFormMixin, ModelForm): """MacroGroup form.""" logo_img = UploadedFileField() initial_editor_users = [] editor_users = UsersChoiceField(label=_('Editor users'), queryset=User.objects.filter(groups__name__in=[G3W_EDITOR1]) .order_by('last_name'), required=False) def __init__(self, *args, **kwargs): if kwargs['initial'].has_key('editor_users'): self.initial_editor_users = kwargs['initial']['editor_users'] super(MacroGroupForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('ACL Users'))), Div( HTML( "<button class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"), css_class='box-tools', ), css_class='box-header with-border' ), Div( Field('editor_users', **{'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;'}), css_class='box-body' ), css_class='box box-solid {} {}'.format('bg-purple', self.checkEmptyInitialsData('editor_users')) ), css_class='{}'.format('col-md-12') ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('General data'))), css_class='box-header with-border' ), Div( 'title', 'use_title_logo_client', Field('description', css_class='wys5', style="width:100%;"), 'logo_img', HTML( """<img {% if not form.logo_img.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.logo_img.value }}">""", ), 'form_id', 'upload_url', 'delete_url', css_class='box-body' ), css_class='box box-success' ), css_class='col-md-12' ), css_class='row' ) ) class Meta: model = MacroGroup fields = '__all__' def save(self, commit=True): instance = super(MacroGroupForm, self).save(commit) # add or remove permissions to editor1 current_editors = [o.id for o in self.cleaned_data['editor_users']] self.instance.remove_permissions_to_editors(list(set(self.initial_editor_users) - set(current_editors))) self.instance.add_permissions_to_editors(list(set(current_editors) - set(self.initial_editor_users))) return instance
class ExampleForm(FileFormMixin,Form): input_file = UploadedFileField()
class GeneralSuiteDataForm(FileFormMixin, ModelForm): """General suite data form.""" suite_logo = UploadedFileField(required=False) def __init__(self, *args, **kwargs): super(GeneralSuiteDataForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('Frontend home data'))), css_class='box-header with-border' ), Div( 'title', 'sub_title', Field('home_description', css_class='wys5', style="width:100%;"), 'suite_logo', 'form_id', 'upload_url', 'delete_url', HTML( """{% if form.suite_logo.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.suite_logo.value }}">{% endif %}""", ), PrependedText('url_suite_logo', '<i class="fa fa-link"></i>'), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend about data'))), css_class='box-header with-border' ), Div( 'about_title', 'about_name', 'about_tel', 'about_email', 'about_address', Field('about_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend groups map data'))), css_class='box-header with-border' ), Div( 'groups_title', Field('groups_map_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend login data'))), css_class='box-header with-border' ), Div( Field('login_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend social data'))), css_class='box-header with-border' ), Div( PrependedText('facebook_url', '<i class="fa fa-facebook"></i>'), PrependedText('twitter_url', '<i class="fa fa-twitter"></i>'), PrependedText('googleplus_url', '<i class="fa fa-google-plus"></i>'), PrependedText('youtube_url', '<i class="fa fa-youtube"></i>'), PrependedText('instagram_url', '<i class="fa fa-instagram"></i>'), PrependedText('flickr_url', '<i class="fa fa-flickr"></i>'), PrependedText('tripadvisor_url', '<i class="fa fa-tripadvisor"></i>'), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format( _('Map client data'))), css_class='box-header with-border' ), Div( 'main_map_title', Field('credits', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), css_class='row' ) ) class Meta: model = GeneralSuiteData fields = '__all__'
class UploadPictureForm(FileFormMixin, forms.Form): input_file = UploadedFileField()
class G3WUserForm(G3WRequestFormMixin, G3WFormMixin, FileFormMixin, UserCreationForm): department = ModelChoiceField(queryset=Department.objects.all(), required=False) backend = ChoiceField(choices=USER_BACKEND_TYPES) avatar = UploadedFileField(required=False) groups = ModelMultipleChoiceField( queryset=AuthGroup.objects.filter( name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1]), required=True, help_text=_('Select roles for this user'), label=_('Main roles')) user_groups_editor = ModelMultipleChoiceField( queryset=AuthGroup.objects.filter( ~Q(name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1, G3W_VIEWER2]), grouprole__role='editor'), required=False, help_text= _('Select <b>EDITOR groups</b> for this user, only Editor Level 2 can be added' ), label=_('User editor groups')) user_groups_viewer = ModelMultipleChoiceField( queryset=AuthGroup.objects.filter( ~Q(name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1, G3W_VIEWER2]), grouprole__role='viewer'), required=False, help_text= _('Select <b>VIEWER groups</b> for this user, only Viewer Level 1 can be added' ), label=_('User viewer groups')) def _set_editor1_queryset(self): """ Set correct guardian queryset for editor level 1 """ self.fields['user_groups_editor'].queryset = get_objects_for_user( self.request.user, 'auth.change_group', AuthGroup).order_by('name').filter(grouprole__role='editor') self.fields['user_groups_viewer'].queryset = get_objects_for_user( self.request.user, 'auth.change_group', AuthGroup).order_by('name').filter(grouprole__role='viewer') def __init__(self, *args, **kwargs): super(G3WUserForm, self).__init__(*args, **kwargs) #filter fileds by role: self.filterFieldsByRoles(**kwargs) #check for groups in intials data if 'groups' in self.initial and len(self.initial['groups']) > 0: self.initial['groups'] = self.initial['groups'] if 'user_groups' in self.initial and len( self.initial['user_groups']) > 0: self.initial['user_groups'] = self.initial['user_groups'] # change queryset for editor1 if G3W_EDITOR1 in getUserGroups(self.request.user): self._set_editor1_queryset() self.helper = FormHelper(self) self.helper.form_tag = False args = [ Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Anagraphic'))), css_class='box-header with-border'), Div( 'first_name', 'last_name', 'email', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-users'></i> {}</h3>" .format(_('ACL/Roles'))), css_class='box-header with-border'), Div(*self.__authrole_fields(), css_class='box-body'), css_class='box box-solid bg-teal-gradient'), css_class='col-md-6 {}'.format( self.checkFieldsVisible('is_superuser', 'is_staff', 'groups'))), css_class='row'), Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-lock'></i> {}</h3>". format(_('Login data'))), css_class='box-header with-border'), Div( PrependedText('username', '<i class="fa fa-user"></i>'), PrependedText('password1', '<i class="fa fa-lock"></i>'), PrependedText('password2', '<i class="fa fa-lock"></i>'), css_class='box-body', ), css_class='box box-danger'), css_class='col-md-6'), Div(Div( Div( HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>" .format(_('User data'))), css_class='box-header with-border'), Div( 'department', 'avatar', HTML( """{% if form.avatar.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.avatar.value }}">{% endif %}""", ), 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row') ] # add backed if user id admin01 if self.request.user.is_superuser and self.request.user.is_staff: args.append( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>". format(_('User backend'))), css_class='box-header with-border'), Div( 'backend', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row')) self.helper.layout = Layout(*args) def __authrole_fields(self): """ Get fields for ACL box if they are into self.fields """ fields = [] if 'is_superuser' in self.fields: fields.append('is_superuser') if 'is_staff' in self.fields: fields.append('is_staff') if 'groups' in self.fields: fields.append( Field( 'groups', **{ 'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;' })) if 'user_groups_editor' in self.fields: fields.append( Field( 'user_groups_editor', **{ 'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;' })) if 'user_groups_viewer' in self.fields: fields.append( Field( 'user_groups_viewer', **{ 'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;' })) return fields def filterFieldsByRoles(self, **kwargs): if self.request.user.is_superuser: if not self.request.user.is_staff: self.fields.pop('is_staff') self.fields.pop('backend') elif G3W_EDITOR1 in getUserGroups(self.request.user): # other but only Editor level 1 can add user # if user is not himself if 'instance' in kwargs and kwargs['instance'] == self.request.user: self.fields.pop('groups') else: self.fields['groups'].queryset = AuthGroup.objects.filter( name__in=[G3W_EDITOR2, G3W_VIEWER1]) self.fields['groups'].required = True self.fields.pop('is_superuser') self.fields.pop('is_staff') self.fields.pop('backend') else: self.fields.pop('is_superuser') self.fields.pop('is_staff') self.fields.pop('groups') self.fields.pop('department') self.fields.pop('backend') # remove groups required is is_superuser or is_staff is set # 'on' 'off' come from icheck if 'data' in kwargs and ('is_superuser' in kwargs['data'] or 'is_staff' in kwargs['data']): if ('is_superuser' in kwargs['data'] and (kwargs['data']['is_superuser'] == 'on' or kwargs['data']['is_superuser'] is True)) or \ ('is_staff' in kwargs['data'] and (kwargs['data']['is_staff'] == 'on' or kwargs['data']['is_superuser'] is True)): self.fields['groups'].required = False def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) # if editor maps groups user add viewer maps groups group to the user saved if commit: if self.cleaned_data['password1']: user.set_password(self.cleaned_data['password1']) user.save() # for save groups if 'groups' not in self.cleaned_data: self.cleaned_data['groups'] = self.request.user.groups.all() else: if self.cleaned_data['groups']: self.cleaned_data['groups'] = self.cleaned_data['groups'] else: self.cleaned_data['groups'] = [] if 'user_groups_editor' in self.cleaned_data and self.cleaned_data[ 'user_groups_editor']: if self.cleaned_data['groups']: self.cleaned_data['groups'] |= self.cleaned_data[ 'user_groups_editor'] else: self.cleaned_data['groups'] = self.cleaned_data[ 'user_groups_editor'] if 'user_groups_viewer' in self.cleaned_data and self.cleaned_data[ 'user_groups_viewer']: if self.cleaned_data['groups']: self.cleaned_data['groups'] |= self.cleaned_data[ 'user_groups_viewer'] else: self.cleaned_data['groups'] = self.cleaned_data[ 'user_groups_viewer'] # if is_superuser or is_staff are set, remove groups if ('is_superuser' in self.cleaned_data or 'is_staff' in self.cleaned_data) and \ (('is_superuser' in self.cleaned_data and self.cleaned_data['is_superuser']) or ('is_staff' in self.cleaned_data and self.cleaned_data['is_staff'])): self.cleaned_data['groups'] = [] self.cleaned_data['user_groups_editor'] = [] self.cleaned_data['user_groups_viewer'] = [] self.save_m2m() if hasattr(user, 'userdata'): if 'department' in self.cleaned_data: user.userdata.department = self.cleaned_data['department'] if self.cleaned_data['avatar']: user.userdata.avatar = self.cleaned_data['avatar'] else: user.userdata.avatar = None user.userdata.save() else: Userdata(user=user, department=self.cleaned_data['department'], avatar=self.cleaned_data['avatar']).save() # add backend if 'backend' in self.cleaned_data: if hasattr(user, 'userbackend'): user.userbackend.backend = self.cleaned_data['backend'] user.userbackend.save() else: Userbackend(user=user, backend=self.cleaned_data['backend']).save() elif not hasattr(user, 'userbackend'): Userbackend(user=user, backend=USER_BACKEND_DEFAULT).save() # add add_group permissions to editor1 add_group = Permission.objects.get( codename='add_group', content_type=ContentType.objects.get_for_model(AuthGroup)) if userHasGroups(user, [G3W_EDITOR1]): user.user_permissions.add(add_group) else: user.user_permissions.remove(add_group) return user def clean_groups(self): """ Check for roles(groups) user can't be editor level 1 and 2 at same time. :return: cleaned_data modified """ groups = self.cleaned_data['groups'] if len( set(groups).intersection( set( AuthGroup.objects.filter( name__in=[G3W_EDITOR1, G3W_EDITOR2])))) == 2: raise ValidationError(_( 'User can\'t be Editor level 1 and at same time Editor level 2' ), code='groups_invalid') return groups def clean_user_groups_editor(self): """ Check only Editor level 2 users can belong to user groups editor. :return: cleaned_data """ user_groups_editor = self.cleaned_data['user_groups_editor'] if user_groups_editor and 'groups' in self.cleaned_data and len( set(self.cleaned_data['groups']).intersection( set(AuthGroup.objects.filter( name__in=[G3W_EDITOR2])))) == 0: raise ValidationError(_( 'User can\'t belong a **editor groups** if he isn\'t a Editor level 2' ), code='user_groups_editor_invalid') return user_groups_editor def clean_user_groups_viewer(self): """ Check only Viewer level 1 users can belong to user groups editor. :return: cleaned_data """ user_groups_viewer = self.cleaned_data['user_groups_viewer'] if user_groups_viewer and 'groups' in self.cleaned_data and len( set(self.cleaned_data['groups']).intersection( set(AuthGroup.objects.filter( name__in=[G3W_VIEWER1])))) == 0: raise ValidationError(_( 'User can\'t belong a **viewer groups** if he isn\'t a Viewer level 1' ), code='user_groups_editor_invalid') return user_groups_viewer def clean_avatar(self): """ Check if upalod file is a valid image by pillow :return: File object Cleaned data """ avatar = self.cleaned_data['avatar'] if avatar is None: return avatar try: image = Image.open(avatar) image.verify() except Exception: raise ValidationError(_('Avatar is no a valid image'), code='image_invalid') return avatar class Meta(UserCreationForm.Meta): fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2', 'is_superuser', 'is_staff', 'groups', 'department', 'avatar', 'user_groups_editor', 'user_groups_viewer') widgets = { #'groups': G3WM2MSingleSelect }
class ManageFolderForm(FileFormMixin, forms.ModelForm): """ Manage folder (in the modal). """ image = UploadedFileField(required=False) parent = OnlyNameChoiceField(queryset=Folder.objects.all(), empty_label=_(u'(None)'), label=_(u'Parent folder'), required=False, widget=Select2Widget()) subscriptions = OnlyNameMultipleChoiceField( label=_(u'Subscriptions'), queryset=Subscription.objects.none(), required=False, widget=Select2MultipleWidget(), help_text=_(u'These are the ones held directly by the folder; they ' u'are displayed above subfolders. There can be none, if ' u'you prefer dispatching your subscriptions in subfolders ' u'only.')) class Meta: model = Folder fields = ( 'name', 'slug', 'image_url', 'parent', # 'is_shared', 'is_moderated', 'is_restricted', # 'anonymous_membership', ) # widgets = { # 'name': forms.TextInput(), # } def __init__(self, *args, **kwargs): """ init(me). """ self.folder_owner = kwargs.pop('owner') super(ManageFolderForm, self).__init__(*args, **kwargs) folders_tree = self.folder_owner.get_folders_tree(for_parent=True) if self.instance.id: try: folders_tree.exclude(id=self.instance.id) except ValueError: pass else: for f in self.instance.children_tree: try: folders_tree.exclude(id=f.id) except ValueError: # ValueError: list.remove(x): x not in list # Happens when try to remove a level-N+ folder # from a list limited to level N-1 folder. No # need to continue, folders_tree return a # depth-aware list. break try: self.fields['subscriptions'].initial = \ self.folder_owner.subscriptions_by_folder[self.instance] except KeyError: # No subscriptions in this folder yet. pass self.fields['parent'].queryset = folders_tree self.fields['subscriptions'].queryset = \ self.folder_owner.subscriptions.order_by('name') def clean_parent(self): """ Return root if no parent selected. """ try: parent = self.cleaned_data['parent'] except: return self.folder_owner.root_folder if parent is None: return self.folder_owner.root_folder return parent def is_valid(self): """ Check a lot of internal stuff to be useful to the user. """ res = super(ManageFolderForm, self).is_valid() if not res: return False if self.instance.id is None: parent_folder = self.cleaned_data['parent'] try: Folder.objects.get(user=self.folder_owner, name=self.cleaned_data['name'], parent=parent_folder) except Folder.DoesNotExist: return True else: if parent_folder == self.folder_owner.root_folder: self._errors['already_exists'] = \ _(u'A top folder by that name already exists.') else: self._errors['already_exists'] = \ _(u'A folder by that name already exists ' u'at the same place.') return False return True def save(self, commit=True): """ Save folder and synchronize_subscriptions_folders(). """ if self.cleaned_data['image']: self.instance.image = self.cleaned_data['image'] else: self.instance.image = None parent_folder = self.cleaned_data.get('parent') parent_changed = False # id == None means creation, else we are editing. if self.instance.id: # We need to get the previous values; Django doesn't cache # them and self.instance is already updated with new values. old_folder = Folder.objects.get(id=self.instance.id) if old_folder.parent != parent_folder: # The form.save() will set the new parent, but # will not unset instance from parent.children. # We need to take care of this. try: old_folder.parent.children.remove(self.instance) except AttributeError: # A top folder is becoming a sub-folder. It had no parent. pass parent_changed = True else: # In "add folder" mode, parent has always changed, it's new! parent_changed = True folder = super(ManageFolderForm, self).save(commit=False) if self.instance.id is None: folder.user = self.folder_owner if commit: folder.save() if parent_changed: # In edit or create mode, we need to take care of the other # direction of the double-linked relation. This will imply # a superfluous write in case of an unchanged parent parent_folder.children.add(folder) self.synchronize_subscriptions_folders(folder) self.delete_temporary_files() return folder def synchronize_subscriptions_folders(self, folder): """ Move subscriptions from old folder to new, given user prefs. .. note:: `folder` is just self.instance passed through to avoid to look it up again. """ try: initial_subscriptions = \ self.folder_owner.subscriptions_by_folder[self.instance] except KeyError: initial_subscriptions = [] updated_subscriptions = self.cleaned_data['subscriptions'] for subscription in initial_subscriptions: if subscription not in updated_subscriptions: subscription.folders.remove(folder) if self.folder_owner.preferences.selector.subscriptions_in_multiple_folders: # NOQA replace_folders = False else: replace_folders = True for subscription in updated_subscriptions: # This will update more things than needed, but in the case of # a changed preference, this will make the subscription appear # in one folder only again. # TODO: when the preference has a trigger on save() that do # this automatically, uncomment the following line to simply # move new subscriptions to this folder, and not touch others. # # if subscription not in initial_subscriptions: if replace_folders: subscription.folders.clear() subscription.folders.add(folder)
class G3WUserForm(G3WRequestFormMixin, G3WFormMixin, FileFormMixin, UserCreationForm): department = ModelChoiceField(queryset=Department.objects.all(), required=False) backend = ChoiceField(choices=(), required=True) avatar = UploadedFileField(required=False) groups = ModelChoiceField(queryset=AuthGroup.objects.all(), required=False, help_text=_('Select group for this user'), label=_('Group')) def __init__(self, *args, **kwargs): super(G3WUserForm, self).__init__(*args, **kwargs) #filter fileds by role: self.filterFieldsByRoles() if 'backend' in self.fields: self.fields['backend'].choices = USER_BACKEND_TYPES #check for groups in intials data if 'groups' in self.initial and len(self.initial['groups']) > 0: self.initial['groups'] = self.initial['groups'][0] self.helper = FormHelper(self) self.helper.form_tag = False args = [ Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Anagraphic'))), css_class='box-header with-border'), Div( 'first_name', 'last_name', 'email', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-users'></i> {}</h3>" .format(_('ACL/Roles'))), css_class='box-header with-border'), Div('is_superuser', 'is_staff', 'groups', css_class='box-body'), css_class='box box-solid bg-teal-gradient'), css_class='col-md-6 {}'.format( self.checkFieldsVisible('is_superuser', 'is_staff', 'groups'))), css_class='row'), Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-lock'></i> {}</h3>". format(_('Login data'))), css_class='box-header with-border'), Div( PrependedText('username', '<i class="fa fa-user"></i>'), PrependedText('password1', '<i class="fa fa-lock"></i>'), PrependedText('password2', '<i class="fa fa-lock"></i>'), css_class='box-body', ), css_class='box box-danger'), css_class='col-md-6'), Div(Div( Div( HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>" .format(_('User data'))), css_class='box-header with-border'), Div( 'department', 'avatar', HTML( """{% if form.avatar.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.avatar.value }}">{% endif %}""", ), 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row') ] # add backed if user id admin01 if self.request.user.is_superuser and self.request.user.is_staff: args.append( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>". format(_('User backend'))), css_class='box-header with-border'), Div( 'backend', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row')) self.helper.layout = Layout(*args) def filterFieldsByRoles(self): if self.request.user.is_superuser: if not self.request.user.is_staff: self.fields.pop('is_staff') self.fields.pop('backend') elif G3W_EDITOR1 in getUserGroups(self.request.user): # other but only Editor level 1 can add user self.fields['groups'].queryset = AuthGroup.objects.filter( name__in=[G3W_VIEWER1, G3W_VIEWER2]) self.fields['groups'].required = True self.fields.pop('is_superuser') self.fields.pop('is_staff') self.fields.pop('backend') elif userHasGroups(self.request.user, [G3W_VIEWER1, G3W_VIEWER2]): self.fields.pop('is_superuser') self.fields.pop('is_staff') self.fields.pop('groups') self.fields.pop('department') self.fields.pop('backend') def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) # if editor maps groups user add viewer maps groups group to the user saved if commit: if self.cleaned_data['password1']: user.set_password(self.cleaned_data['password1']) user.save() # for save groups if 'groups' not in self.cleaned_data: self.cleaned_data['groups'] = self.request.user.groups.all() else: if self.cleaned_data['groups']: self.cleaned_data['groups'] = ( self.cleaned_data['groups'], ) else: self.cleaned_data['groups'] = [] self.save_m2m() if hasattr(user, 'userdata'): if 'department' in self.cleaned_data: user.userdata.department = self.cleaned_data['department'] if self.cleaned_data['avatar']: user.userdata.avatar = self.cleaned_data['avatar'] else: user.userdata.avatar = None user.userdata.save() else: Userdata(user=user, department=self.cleaned_data['department'], avatar=self.cleaned_data['avatar']).save() # add backend if 'backend' in self.cleaned_data: if hasattr(user, 'userbackend'): user.userbackend.backend = self.cleaned_data['backend'] user.userbackend.save() else: Userbackend(user=user, backend=self.cleaned_data['backend']).save() elif not hasattr(user, 'userbackend'): Userbackend(user=user, backend=USER_BACKEND_DEFAULT).save() return user def clean_avatar(self): """ Check if upalod file is a valid image by pillow :return: File object Cleaned data """ avatar = self.cleaned_data['avatar'] if avatar is None: return avatar try: image = Image.open(avatar) image.verify() except Exception: raise ValidationError(_('Avatar is no a valid image'), code='image_invalid') return avatar class Meta(UserCreationForm.Meta): fields = ( 'first_name', 'last_name', 'email', 'username', 'password1', 'password2', 'is_superuser', 'is_staff', 'groups', 'department', 'avatar', ) widgets = { #'groups': G3WM2MSingleSelect }
class ManageSubscriptionForm(FileFormMixin, forms.ModelForm): """ Edit subscription properties. """ thumbnail = UploadedFileField(required=False) class Meta: model = Subscription # NOTE: as we manage `folders` differently and very specially, given # the value of a user preference, we MUST NOT put `folders` here in # `fields`, because in one of 2 cases, setting the initial value will # not work because of attribute being a list and field being not. fields = ( 'name', 'notes', 'thumbnail_url', ) # widgets = { # 'name': forms.TextInput(), # } def __init__(self, *args, **kwargs): """ init(me). """ super(ManageSubscriptionForm, self).__init__(*args, **kwargs) folders_queryset = self.instance.user.folders_tree preferences = self.instance.user.preferences if preferences.selector.subscriptions_in_multiple_folders: self.fields['folders'] = OnlyNameMultipleChoiceField( queryset=folders_queryset, required=False, label=_(u'Folders'), widget=Select2MultipleWidget(), initial=self.instance.folders.all()) # no empty_label here. else: self.fields['folders'] = OnlyNameChoiceField( queryset=folders_queryset, required=False, widget=Select2Widget(), label=_(u'Folder'), empty_label=_(u'(None)')) try: self.fields['folders'].initial = self.instance.folders.all()[0] except IndexError: # Subscription is not in any folder yet. pass def save(self, commit=True): """ Save the form, Luke. """ subscription = super(ManageSubscriptionForm, self).save(commit=False) preferences = subscription.user.preferences.selector if self.cleaned_data['thumbnail']: subscription.thumbnail = self.cleaned_data['thumbnail'] else: subscription.thumbnail = None # Handle `folders` manually, because it's not in form.fields. if preferences.subscriptions_in_multiple_folders: if self.cleaned_data['folders']: subscription.folders = self.cleaned_data['folders'] elif self.cleaned_data['folders'] is not None: # Avoid the: # - 'folders : Saisissez une liste de valeurs.' error. # - A ReferenceField only accepts DBRef or documents: ['folders'] # when nothing is selected, this makes value=[None]. # # In "one folder only", we used a "select" widget which didn't # built a list. We need to reconstruct it for the save() to work. subscription.folders = [self.cleaned_data['folders']] elif self.cleaned_data['folders'] is None: # User emptied the folder field. The subscription is back to # “un-sorted” pseudo-folder. subscription.folders = [] if commit: subscription.save() self.delete_temporary_files() return subscription
class QdjangoProjetForm(TranslationModelForm, QdjangoProjectFormMixin, G3WFormMixin, G3WGroupFormMixin, G3WGroupBaseLayerFormMixin, G3WRequestFormMixin, G3WACLForm, FileFormMixin, forms.ModelForm): qgis_file = UploadedFileField(required=True) thumbnail = UploadedFileField(required=False) url_alias = forms.CharField( required=False, label=_('URL alias'), help_text=_( 'You can set a human readable URL for the map. Only alphanumeric characters, not white space or ' 'special characters')) def __init__(self, *args, **kwargs): if 'instance' in kwargs and hasattr(kwargs['instance'], 'url_alias'): kwargs['initial']['url_alias'] = kwargs['instance'].url_alias super(QdjangoProjetForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='ion ion-map'></i> {}</h3>". format(_('Qgis Project'))), css_class='box-header with-border'), Div( 'qgis_file', 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), crispyBoxACL(self), crispyBoxBaseLayer(self), css_class='row'), Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Description data'))), css_class='box-header with-border'), Div( 'title_ur', Field('description', css_class='wys5'), 'thumbnail', HTML( """<img {% if not form.thumbnail.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.thumbnail.value }}">""", ), 'url_alias', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), Div(Div(Div(HTML( "<h3 class='box-title'><i class='ion ion-gear'></i> {}</h3>" .format(_('Options and actions'))), css_class='box-header with-border'), Div( 'feature_count_wms', 'multilayer_query', 'multilayer_querybybbox', 'multilayer_querybypolygon', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), css_class='row'), ) class Meta: model = Project fields = ('qgis_file', 'description', 'thumbnail', 'baselayer', 'feature_count_wms', 'multilayer_query', 'multilayer_querybybbox', 'multilayer_querybypolygon', 'title_ur') def _setEditorUserQueryset(self): """ Set query set for editors chosen fields :return: None """ # add filter by group permissions editor_group = get_users_for_object(self.group, 'change_group', [G3W_EDITOR1]) editor2_group = get_users_for_object(self.group, 'add_project_to_group', [G3W_EDITOR2]) self.fields['editor_user'].queryset = get_objects_for_user(self.request.user, 'auth.change_user', User) \ .filter(pk__in=[e.pk for e in editor_group], groups__name__in=self.editor1_groups) self.fields['editor2_user'].queryset = get_objects_for_user(self.request.user, 'auth.change_user', User) \ .filter(pk__in=[e.pk for e in editor2_group], groups__name__in=self.editor2_groups) def _setViewerUserQueryset(self, **kwargs): """ Set queryset for viewers chosen fields Take Viewers level 1 from Group :return: None """ # get viewers from groups viewers = get_viewers_for_object(self.group, self.request.user, 'view_group') # get queryset self.fields['viewer_users'].queryset = User.objects.filter( groups__name__in=self.viewer_groups, pk__in=[v.pk for v in viewers]) def _set_user_groups_queryset(self): """ Set query set for viewer user groups chosen fields Take Viewer User Groups from Group :return: None """ super(QdjangoProjetForm, self)._set_user_groups_queryset() editor_user_groups = get_user_groups_for_object( self.group, self.request.user, 'view_group', 'editor') self.fields['editor_user_groups'].queryset = AuthGroup.objects.filter( pk__in=[v.pk for v in editor_user_groups]) viewer_user_groups = get_user_groups_for_object( self.group, self.request.user, 'view_group', 'viewer') self.fields['viewer_user_groups'].queryset = AuthGroup.objects.filter( pk__in=[v.pk for v in viewer_user_groups]) def save(self, commit=True): self._ACLPolicy() self._save_url_alias() # add permission to Editor level 1 and 2 if current user is Editor level 1 or 2 if userHasGroups(self.request.user, [G3W_EDITOR1, G3W_EDITOR2]): self.instance.addPermissionsToEditor(self.request.user) # give permission to Editor level 1 of group id user is Editor level 2 if userHasGroups(self.request.user, [G3W_EDITOR2]): # give permission to user groups of map group user_editor_groups = get_groups_for_object( self.instance.group, 'view_group', 'editor') self.instance.add_permissions_to_editor_user_groups( [uge.pk for uge in user_editor_groups]) editor_users = get_users_for_object(self.instance.group, 'view_group', [G3W_EDITOR1, G3W_EDITOR2]) for eu in editor_users: self.instance.addPermissionsToEditor(eu)
class QdjangoProjetForm(QdjangoProjectFormMixin, G3WFormMixin, G3WGroupFormMixin, G3WGroupBaseLayerFormMixin, G3WRequestFormMixin, G3WACLForm, FileFormMixin, forms.ModelForm): qgis_file = UploadedFileField(required=True) thumbnail = UploadedFileField(required=False) def __init__(self, *args, **kwargs): super(QdjangoProjetForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='ion ion-map'></i> {}</h3>". format(_('Qgis Project'))), css_class='box-header with-border'), Div( 'qgis_file', 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), crispyBoxACL(self), crispyBoxBaseLayer(self), Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Descrition data'))), css_class='box-header with-border'), Div( Field('description', css_class='wys5'), 'thumbnail', HTML( """<img {% if not form.thumbnail.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.thumbnail.value }}">""", ), css_class='box-body', ), css_class='box box-success'), css_class='col-md-12'), css_class='row')) class Meta: model = Project fields = ('qgis_file', 'description', 'thumbnail', 'baselayer') widgets = { ''' 'qgis_file': DropzoneInput(dropzone_config={ 'url': '/file-upload/', 'maxFiles':1} ) ''' } def save(self, commit=True): self._ACLPolicy() # add permission to editor1 if current user is editor1 if userHasGroups(self.request.user, [G3W_EDITOR1]): self.instance.addPermissionsToEditor(self.request.user)