Ejemplo n.º 1
0
 def form_valid(self, form):
     if self.is_model_form():
         try:
             self.object = form.save(commit=True, request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
     return FormMixin.form_valid(self, form)
Ejemplo n.º 2
0
 def form_valid(self, form):
     """
     Assign datatype data inside a transaction object
     """
     with transaction.atomic():
         form.instance.author = self.request.user
         form.instance.generic = False
         form.instance.community = Community.objects.get(
             id=self.kwargs.get('community_id'))
         form.instance.save()
         property_title = Property(datatype=form.instance,
                                   author=self.request.user,
                                   name='Title',
                                   type=0,
                                   generic=1,
                                   required=True)
         property_title.save()
         property_semantic_tag = Property(datatype=form.instance,
                                          author=self.request.user,
                                          name='Semantic Tags',
                                          type=0,
                                          generic=1,
                                          required=True)
         property_semantic_tag.save()
         return FormMixin.form_valid(self, form)
Ejemplo n.º 3
0
    def get(self, request, *args, **kwargs):
        self.object = SingleObjectMixin.get_object(self)
        if not request.user.has_perm('catalog.can_mark_returned'):
            return HttpResponseRedirect(reverse('books'))

        return render(request, 'catalog/book_form.html',
                      FormMixin.get_context_data(self, **kwargs))
Ejemplo n.º 4
0
    def get(self, request, *args, **kwargs):
        self.object = None
        if not request.user.has_perm('catalog.can_mark_returned'):
            return HttpResponseRedirect(reverse('authors'))

        return render(request, 'catalog/author_form.html',
                      FormMixin.get_context_data(self, **kwargs))
Ejemplo n.º 5
0
    def form_valid(self, form):
        # check if new task with picked user already exists
        if form.cleaned_data['state'] == 'S' and self.kwargs.get(
                'task_id') is None:
            exists_task = Task.objects.filter(abon=form.cleaned_data['abon'],
                                              state='S')
            if exists_task.exists():
                messages.info(
                    self.request,
                    _('New task with this user already exists.'
                      ' You are redirected to it.'))
                return redirect('taskapp:edit', exists_task.first().pk)

        try:
            self.object = form.save()
            if self.object.author is None:
                self.object.author = self.request.user
                self.object.save(update_fields=('author', ))
            task_id = safe_int(self.kwargs.get('task_id', 0))
            if task_id == 0:
                log_text = _('Task has successfully created')
            else:
                log_text = _('Task has changed successfully')
            messages.add_message(self.request, messages.SUCCESS, log_text)
            self.object.send_notification()
        except MultipleException as e:
            for err in e.err_list:
                messages.add_message(self.request, messages.WARNING, err)
        except TaskException as e:
            messages.add_message(self.request, messages.ERROR, e)
        return FormMixin.form_valid(self, form)
Ejemplo n.º 6
0
    def form_valid(self, form):
        # check if new task with picked user already exists
        if form.cleaned_data['state'] == 'S' and self.kwargs.get('task_id') is None:
            exists_task = Task.objects.filter(abon=form.cleaned_data['abon'], state='S')
            if exists_task.exists():
                messages.info(self.request, _('New task with this user already exists.'
                                              ' You are redirected to it.'))
                return redirect('taskapp:edit', exists_task.first().pk)

        try:
            self.object = form.save()
            if self.object.author is None:
                self.object.author = self.request.user
                self.object.save(update_fields=('author',))
            task_id = safe_int(self.kwargs.get('task_id', 0))
            if task_id == 0:
                log_text = _('Task has successfully created')
            else:
                log_text = _('Task has changed successfully')
            messages.add_message(self.request, messages.SUCCESS, log_text)
            self.object.send_notification()
        except MultipleException as e:
            for err in e.err_list:
                messages.add_message(self.request, messages.WARNING, err)
        except TaskException as e:
            messages.add_message(self.request, messages.ERROR, e)
        return FormMixin.form_valid(self, form)
Ejemplo n.º 7
0
 def form_valid(self, form):
     repo_url = form.cleaned_data["repo_url"]
     _, name = repo_url.rsplit("/", 1)
     self.object = App.objects.create(
         name=name,
         repo_url=repo_url,
     )
     if form.cleaned_data.get("new_datasource_name"):
         bucket = S3Bucket.objects.create(
             name=form.cleaned_data["new_datasource_name"], )
         AppS3Bucket.objects.create(
             app=self.object,
             s3bucket=bucket,
             access_level='readonly',
         )
         UserS3Bucket.objects.create(
             user=self.request.user,
             s3bucket=bucket,
             access_level='readwrite',
             is_admin=True,
         )
     elif form.cleaned_data.get("existing_datasource_id"):
         AppS3Bucket.objects.create(
             app=self.object,
             s3bucket=form.cleaned_data["existing_datasource_id"],
             access_level='readonly',
         )
     UserApp.objects.create(
         app=self.object,
         user=self.request.user,
         is_admin=True,
     )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 8
0
 def get_form_kwargs(self):
     """
     Returns the keyword arguments for instantiating the formset.
     """
     kwargs = FormMixin.get_form_kwargs(self)
     kwargs.update({'queryset': self.get_queryset()})
     return kwargs
Ejemplo n.º 9
0
    def get_form_kwargs(self):
        kwargs = FormMixin.get_form_kwargs(self)

        if self.request.method in ('POST', 'PUT'):
            kwargs['data'] = self.request.data

        return kwargs
Ejemplo n.º 10
0
 def form_valid(self,form):
     if self.is_model_form():
         try:
             self.object = form.save(commit=True,request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
     return FormMixin.form_valid(self,form)
Ejemplo n.º 11
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     self.object.type = self.kwargs['type']
     self.object.save()
     gm = GameUser(gamemaster=self.request.user, game=self.object)
     gm.save()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 12
0
 def get_form_kwargs(self):
     """
     Returns the keyword arguments for instanciating the form.
     """
     kwargs = FormMixin.get_form_kwargs(self)
     if hasattr(self, 'object'):
         kwargs.update({'instance': self.object})
     return kwargs
Ejemplo n.º 13
0
 def form_valid(self, form):
     new_pic = self.create_pic(self.target, self.request.FILES['pic'])
     if new_pic:
         messages.info(self.request, _("Successfully uploaded a new image."))
     if self.request.is_ajax() or self.request.POST.get('async', None) == 'true':
         return self.ajax_form_valid(new_pic)
     else:
         return FormMixin.form_valid(self, form)
Ejemplo n.º 14
0
 def get_formset_kwargs(self):
     kwargs = FormMixin.get_form_kwargs(self)
     kwargs.update(
         {
             'initial': self.get_formset_initial(),
         }
     )
     return kwargs
Ejemplo n.º 15
0
 def form_valid(self, form):
     new_pic = self.create_pic(self.target, self.request.FILES['pic'])
     if new_pic:
         messages.info(self.request, _("Successfully uploaded a new image."))
     if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':
         return self.ajax_form_valid(new_pic)
     else:
         return FormMixin.form_valid(self, form)
Ejemplo n.º 16
0
 def form_valid(self, form):
     self.task = get_object_or_404(Task, pk=self.kwargs.get('task_id'))
     self.object = form.make_save(author=self.request.user, task=self.task)
     author = self.object.author
     assign_perm('taskapp.change_extracomment', author, self.object)
     assign_perm('taskapp.delete_extracomment', author, self.object)
     assign_perm('taskapp.view_extracomment', author, self.object)
     return FormMixin.form_valid(self, form)
Ejemplo n.º 17
0
 def form_valid(self, form):
     self.object = self.get_object()
     messages.success(self.request,
                      _("Account %(username)s was deleted successfully.") %
                      {'username': self.object.username},
                      extra_tags='modal')
     self.object.delete()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 18
0
 def get_form_kwargs(self):
     """
     Returns the keyword arguments for instanciating the form.
     """
     kwargs = FormMixin.get_form_kwargs(self)
     if hasattr(self,'object'):
         kwargs.update({'instance': self.object})
     return kwargs
Ejemplo n.º 19
0
 def form_valid(self, form):
     if self.is_model_form():
         try:
             self.object = form.save(commit=True, request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
         #if hasattr(self.object,'save_model'):
         #    self.object.save_model(self.request,form,False):
     return FormMixin.form_valid(self, form)
Ejemplo n.º 20
0
 def form_valid(self, form):
     """
     Assign flag data inside a transaction object
     """
     with transaction.atomic():
         form.instance.created_by = self.request.user
         form.instance.instance = Instance.objects.all().filter(id=self.kwargs.get('instance_id')).first()
         form.instance.save()
         return FormMixin.form_valid(self, form)
Ejemplo n.º 21
0
 def form_valid(self, form):
     self.object = form.save(user=self.request.user)
     email = auction_created(self.object, self.request)
     self.object.send_email(email[0], email[1], bidders=False)
     '''
     If we call super (ModelFormMixin) the form will be re-saved and self.object overwritten,
     have to call form_valid in FormMixin to avoid this issue.
     '''
     return FormMixin.form_valid(self, form)
Ejemplo n.º 22
0
    def form_valid(self, form):
        self.object = self.get_result_object(form)
        violations = self.form_violates(form)

        if violations:
            transaction.set_rollback(True)
            return self.form_invalid(form)

        return FormMixin.form_valid(self, form)
Ejemplo n.º 23
0
 def get_form_kwargs(self, **kwargs):
     """
     Override get_form_kwargs to itself take kwargs.
     """
     # our ListForm can't handle the 'instance' kwarg, so we don't call
     # ModelFormMixin as super
     keywords = FormMixin.get_form_kwargs(self)
     keywords.update(kwargs)
     return keywords
 def form_valid(self, form):
     self.object = IAMManagedPolicy(name=form.cleaned_data['name'],
                                    created_by=self.request.user)
     self.object.save()
     messages.success(
         self.request,
         f"Successfully created {self.object.name} policy",
     )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 25
0
 def form_valid(self,form):
     if self.is_model_form():
         try:
             self.object = form.save(commit=True,request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
         #if hasattr(self.object,'save_model'):
         #    self.object.save_model(self.request,form,False):
     return FormMixin.form_valid(self,form)
Ejemplo n.º 26
0
 def form_valid(self, form):
     """
     Assign flag data inside a transaction object
     """
     with transaction.atomic():
         form.instance.source = self.request.user
         form.instance.target = CustomUser.objects.all().filter(
             id=self.kwargs.get('target_id')).first()
         form.instance.save()
         return FormMixin.form_valid(self, form)
 def form_valid(self, form):
     user_id = form.cleaned_data['user_id']
     user = User.objects.get(pk=user_id)
     self.object.users.add(user)
     self.object.save()
     messages.success(
         self.request,
         f"Successfully added user {user.name} ",
     )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 28
0
 def form_valid(self, form):
     self.task = get_object_or_404(Task, pk=self.kwargs.get('task_id'))
     self.object = form.make_save(
         author=self.request.user,
         task=self.task
     )
     author = self.object.author
     assign_perm('taskapp.change_extracomment', author, self.object)
     assign_perm('taskapp.delete_extracomment', author, self.object)
     assign_perm('taskapp.view_extracomment', author, self.object)
     return FormMixin.form_valid(self, form)
Ejemplo n.º 29
0
 def form_valid(self, form):
     new_avatar = self.create_avatar(self.target, self.request.FILES['avatar'])
     if new_avatar:
         self.request.user.message_set.create(
             message=_("Successfully uploaded a new avatar."))
         avatar_updated.send(sender=Avatar, target=self.target,
                             avatar=new_avatar)
     if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':
         return self.ajax_form_valid(new_avatar)
     else:
         return FormMixin.form_valid(self, form)
Ejemplo n.º 30
0
 def form_valid(self,form,**kwargs):
     cur_obj = self.get_for_object(**kwargs)
     form.current_object = cur_obj
     if self.is_model_form():
         try:
             self.object = form.save(commit=True,request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
         #if hasattr(self.object,'save_model'):
         #    self.object.save_model(self.request,form,False):
     return FormMixin.form_valid(self,form)
Ejemplo n.º 31
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     self.object.project = self.project
     user = self.object.user
     if (ProjectMember.objects.filter(project=self.project)
                      .filter(user=user).exists()):
         pass
         # TODO: do not validate the form
     else:
         self.object.save()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 32
0
 def form_valid(self, form, **kwargs):
     cur_obj = self.get_for_object(**kwargs)
     form.current_object = cur_obj
     if self.is_model_form():
         try:
             self.object = form.save(commit=True, request=self.request)
         except TypeError:
             self.object = form.save(commit=True)
         #if hasattr(self.object,'save_model'):
         #    self.object.save_model(self.request,form,False):
     return FormMixin.form_valid(self, form)
Ejemplo n.º 33
0
    def form_valid(self, form):
        new_avatar = Avatar.objects.get(id=form.cleaned_data['choice'])
        new_avatar.primary = True
        new_avatar.save()
        self.request.user.message_set.create(
            message=_("Avatar successfully updated."))
        avatar_updated.send(sender=Avatar, target=self.target, avatar=new_avatar)

        if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':
            return self.ajax_form_valid(new_avatar)
        else:
            return FormMixin.form_valid(self, form)
Ejemplo n.º 34
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     if cls.require_owner_to_update:
         setattr(self.object, cls.owner_field_name, self.request.user)
     if self.parent:
         setattr(
             self.object,
             self.parent.get_fk_name(self.model),
             self.parent.get_object(self.kwargs[self.parent.get_pk_name()]),
         )
     self.object.save()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 35
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     if cls.require_owner_to_update:
         setattr(self.object, cls.owner_field_name,
                 self.request.user)
     if self.parent:
         setattr(
             self.object, self.parent.get_fk_name(self.model),
             self.parent.get_object(
                 self.kwargs[self.parent.get_pk_name()]))
     self.object.save()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 36
0
 def form_valid(self, form):
     self.object = Parameter(key=form.cleaned_data['key'],
                             role_name=form.cleaned_data['role_name'],
                             app_type=form.cleaned_data['app_type'],
                             description="",
                             created_by=self.request.user)
     self.object.value = form.cleaned_data['value']
     self.object.save()
     messages.success(
         self.request,
         f"Successfully created {self.object.name} parameter",
     )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 37
0
 def form_valid(self, form):
     name = form.cleaned_data['name']
     datasource_type = self.request.GET.get("type")
     self.object = S3Bucket.objects.create(
         name=name,
         created_by=self.request.user,
         is_data_warehouse=datasource_type == "warehouse",
     )
     messages.success(
         self.request,
         f"Successfully created {name} {datasource_type} data source",
     )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 38
0
    def form_valid(self, form):
        user = self.request.user
        bucket = get_object_or_404(S3Bucket, pk=self.kwargs['pk'])

        if not user.has_perm('api.grant_s3bucket_access', bucket):
            raise PermissionDenied()

        is_admin = form.cleaned_data.get('is_admin')

        if is_admin and not user.has_perm('api.add_s3bucket_admin', bucket):
            raise PermissionDenied()

        self.object = self.model.objects.create(**self.values(form))
        return FormMixin.form_valid(self, form)
Ejemplo n.º 39
0
    def get_forms(self):
        forms = {}
        for model_conf in self.forms_models:
            if isinstance(model_conf, dict):
                model = model_conf['model']
                foreign_key_field = model_conf.get('field_name', None)
                queryset = model_conf.get('queryset', None)
                factory_kwargs = dict(model_conf) # clone it!
                del factory_kwargs['model']
                if 'field_name' in factory_kwargs:
                    del factory_kwargs['field_name']
                if 'queryset' in factory_kwargs:
                    del factory_kwargs['queryset']
            else:
                factory_kwargs = {}
                model = model_conf
                foreign_key_field = None
                queryset = None
            if foreign_key_field is None:
                # try to auto-detect, just use the first ForeignKey
                # in the model
                for field in model._meta.fields:
                    if isinstance(field, models.ForeignKey):
                        foreign_key_field = field.name
                if foreign_key_field is None:
                    raise ImproperlyConfigured(
                        "MultiBoundObjectFormsMixin.forms_models must contain either models with a ForeignKey or a dictionary of configuration."
                        )
            if queryset is None:
                if not hasattr(self, 'object') or self.object is None:
                    queryset = model.objects.none()
                else:
                    queryset = model.objects.filter(
                        **{
                            foreign_key_field: self.object,
                            }
                          )

            forms[model._meta.object_name.lower()] = bound_object_formset(
                model,
                queryset=queryset,
                field=foreign_key_field,
                initial=lambda: self.new_object,
                **factory_kwargs
                )(
                prefix=model._meta.object_name.lower(),
                **FormMixin.get_form_kwargs(self)
                )

        return forms
Ejemplo n.º 40
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     self.object.sender = self.request.user
     if form.cleaned_data['send']:
         self.object.refcount = 1 + len(form.cleaned_data['receivers'])
         self.object.sending_time = datetime.now()
     else:
         self.object.refcount = 1
     self.object.save()
     for recipient in form.cleaned_data['receivers']:
         copy = UserMessageCopy(message=self.object,
                                user=recipient,
                                copy=form.cleaned_data['send'])
         copy.save()
     return FormMixin.form_valid(self, form)
Ejemplo n.º 41
0
 def form_valid(self, form):
     # TODO this can be replaced with AppS3Bucket.objects.get_or_create()
     try:
         self.object = AppS3Bucket.objects.get(
             s3bucket=form.cleaned_data['datasource'],
             app_id=self.kwargs['pk'],
         )
         self.object.access_level = form.cleaned_data['access_level']
         self.object.save()
     except AppS3Bucket.DoesNotExist:
         self.object = AppS3Bucket.objects.create(
             access_level=form.cleaned_data['access_level'],
             app_id=self.kwargs['pk'],
             s3bucket=form.cleaned_data['datasource'],
         )
     return FormMixin.form_valid(self, form)
Ejemplo n.º 42
0
    def get_form(self, *args, **kwargs):
        """
        Return a form with the organizations limited to the organizations
        this user has access to. Returns a form with all availble
        organizations for super users.

        Since mixin is used in views that subclass CreateView or UpdateView
        I am relying on those to provide the `get_form` as implemented
        in the `FormMixin` both of those inherit
        """
        form = FormMixin.get_form(self, *args, **kwargs)
        if self.request.user.is_superuser:
            return form

        form.controller_form.fields['organization'].queryset = (
            self.request.user.organization_set.all())
        return form
Ejemplo n.º 43
0
    def get_form(self, *args, **kwargs):
        """
        Return a form with the organizations limited to the organizations
        this user has access to. Returns a form with all availble
        organizations for super users.

        Since mixin is used in views that subclass CreateView or UpdateView
        I am relying on those to provide the `get_form` as implemented
        in the `FormMixin` both of those inherit
        """
        form = FormMixin.get_form(self, *args, **kwargs)
        if self.request.user.is_superuser:
            return form

        form.controller_form.fields['organization'].queryset = (
            self.request.user.organization_set.all())
        return form
Ejemplo n.º 44
0
 def form_valid(self, form):
     try:
         self.object = form.save()
         if self.object.author is None:
             self.object.author = self.request.user
             self.object.save(update_fields=('author', ))
         task_id = safe_int(self.kwargs.get('task_id', 0))
         if task_id == 0:
             log_text = _('Task has successfully created')
         else:
             log_text = _('Task has changed successfully')
         messages.add_message(self.request, messages.SUCCESS, log_text)
         self.object.send_notification()
     except MultipleException as e:
         for err in e.err_list:
             messages.add_message(self.request, messages.WARNING, err)
     except TaskException as e:
         messages.add_message(self.request, messages.ERROR, e)
     return FormMixin.form_valid(self, form)
Ejemplo n.º 45
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     if form.cleaned_data['send']:
         self.object.refcount = 1 + len(form.cleaned_data['receivers'])
         self.object.sending_time = datetime.now()
     self.object.save()
     UserMessageCopy.objects.filter(message=self.object).exclude(
         user__in=form.cleaned_data['receivers']).delete()
     old_receivers = UserMessageCopy.objects.filter(message=self.object)
     old_list = old_receivers.values_list('user', flat=True)
     for recipient in form.cleaned_data['receivers']:
         if not recipient.pk in old_list:
             copy = UserMessageCopy(message=self.object,
                                    user=recipient,
                                    copy=False)
             copy.save()
     if form.cleaned_data['send']:
         old_receivers.update(copy=True)
     return FormMixin.form_valid(self, form)
Ejemplo n.º 46
0
 def get_context_data(self, **kwargs):
     context = ListView.get_context_data(self, **kwargs)
     context['filter_string'] = self.get_filter_string()
     context['caption'] = self.caption
     context['description'] = self.description
     if self.show_filter:
         u = FormMixin.get_context_data(self, **kwargs)
         context.update(u)
         context['description'] = 'Найдено {count} котиков'.format(
             count=len(self.object_list))
     else:
         context['description'] = self.description
         del context['form']
     extra_title = context['caption']
     context.update(
         get_base_catsekb_context(active_menu=ANIMALS,
                                  extra_title=extra_title,
                                  project=self.project))
     return context
Ejemplo n.º 47
0
 def form_valid(self, form):
     ids = form.cleaned_data['choices']
     new_avatar = None
     if unicode(self.avatar.id) in ids and self.avatars.count() > len(ids):
         # Find the next best avatar, and set it as the new primary
         for a in self.avatars:
             if unicode(a.id) not in ids:
                 a.primary = True
                 a.save()
                 new_avatar = a
                 avatar_updated.send(sender=Avatar, target=self.target,
                                     avatar=a)
                 break
     Avatar.objects.filter(id__in=ids).delete()
     self.request.user.message_set.create(
         message=_("Successfully deleted the requested avatars."))
     if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':
         return self.ajax_form_valid(new_avatar)
     else:
         return FormMixin.form_valid(self, form)
Ejemplo n.º 48
0
 def get_form_kwargs(self):
     kwargs = FormMixin.get_form_kwargs(self)
     if hasattr(self,'object'):
         kwargs.update({'instance': self.object})
     return kwargs
Ejemplo n.º 49
0
 def get_form_kwargs(self):
     kwargs = FormMixin.get_form_kwargs(self)
     kwargs['target'] = self.target
     kwargs['size'] = self.request.REQUEST.get('size', AVATAR_DEFAULT_SIZE)
     return kwargs
Ejemplo n.º 50
0
 def get_formset_kwargs(self):
     return FormMixin.get_form_kwargs(self)
Ejemplo n.º 51
0
 def form_invalid(self, form):
     self.status = False
     return FormMixin.form_invalid(self, form)
Ejemplo n.º 52
0
 def form_valid(self, formset):
     # TODO: this not work sometimes
     formset.save()
     return FormMixin.form_valid(self, formset)
Ejemplo n.º 53
0
 def form_valid(self, formset):
     formset.save()
     messages.info(self.request, "%s have been updated successfully." % self.model._meta.verbose_name_plural)
     return FormMixin.form_valid(self, formset)
Ejemplo n.º 54
0
 def form_valid(self, form):
     if self.is_ajax():
         self.status = True
         return self.get_ajax_response({'form': form})
     return FormMixin.form_valid(self, form)
Ejemplo n.º 55
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     self.save_object()
     return FormMixin.form_valid(self, form)