Проставляет моделям из набора форм автора
    :param formset: набор форм
    :param user: автор
    :return:
194776
def save_formset_with_author(formset, user):
    
    instances = formset.save(commit=False)
    for obj in formset.deleted_objects:
        obj.delete()
    for instance in instances:
        if user.is_authenticated() and hasattr(instance, 'author') and not instance.author:
            instance.author = user
        instance.save()
    formset.save_m2m()
1156410
def formfield(self, **kwargs):
        

        defaults = {
            'form_class': forms.CharField,
            'required': False
        }

        defaults.update(kwargs)

        form_field = super().formfield(**defaults)
        form_field.widget = forms.HiddenInput()

        return form_field
611030
def show_user(self, user):
        
        res = self.post('loadUsers', {'userId': user})
        if isinstance(res, list) and len(res) > 0:
            res = res[0]
        return _fix_user(res)
1281735
def form_valid(self, form):
        
        response = self.ulogin_response(form.cleaned_data['token'],
                                        self.request.get_host())

        if 'error' in response:
            return render(self.request, self.error_template_name,
                          {'json': response})

        if user_is_authenticated(get_user(self.request)):
            user, identity, registered = \
                self.handle_authenticated_user(response)
        else:
            user, identity, registered = \
                self.handle_anonymous_user(response)

        assign.send(sender=ULoginUser,
                    user=get_user(self.request),
                    request=self.request,
                    registered=registered,
                    ulogin_user=identity,
                    ulogin_data=response)
        return redirect(self.request.GET.get(REDIRECT_FIELD_NAME) or '/')
1053096
def form_valid(self, form):
        
        user_kwargs = (
            {'voter': self.request.user}
            if self.request.user.is_authenticated
            else {'anonymous_key': self.request.user.forum_key}
        )

        if self.object.user_changes:
            # If user changes are allowed for this poll, all the poll associated with the current
            # user must be deleted.
            TopicPollVote.objects.filter(poll_option__poll=self.object, **user_kwargs).delete()

        options = form.cleaned_data['options']
        for option in options:
            TopicPollVote.objects.create(poll_option=option, **user_kwargs)

        return HttpResponseRedirect(self.get_success_url())
24891
public function form(ZorkForm &$form,UserStructure $user)
    {
        $event = new Event\Form();
        $event->setForm($form);
        $event->setUser($user);
        $this->getEventManager()->trigger($event);
        return $event->getForm();   
    }
1060913
def _get_fieldsets_post_form_or_formset(self, request, form, obj=None):
        
        base_fields = self.replace_orig_field(form.base_fields.keys())
        fields = base_fields + list(self.get_readonly_fields(request, obj))
        return [(None, {'fields': self.replace_orig_field(fields)})]
1006296
def view_user(self, user):
        
        log.debug('Viewing user %s', user.username)
        self.cur_user = None
        self.pages_tabw.setCurrentIndex(9)
        self.user_username_le.setText(user.username)
        self.user_first_le.setText(user.first_name)
        self.user_last_le.setText(user.last_name)
        self.user_email_le.setText(user.email)

        prjrootdata = treemodel.ListItemData(['Name', 'Short', 'Path', 'Created', 'Semester', 'Status', 'Resolution', 'FPS', 'Scale'])
        prjrootitem = treemodel.TreeItem(prjrootdata)
        prjs = djadapter.projects.filter(users=user)
        for prj in prjs:
            prjdata = djitemdata.ProjectItemData(prj)
            treemodel.TreeItem(prjdata, prjrootitem)
        self.user_prj_model = treemodel.TreeModel(prjrootitem)
        self.user_prj_tablev.setModel(self.user_prj_model)

        taskrootdata = treemodel.ListItemData(['Name'])
        taskrootitem = treemodel.TreeItem(taskrootdata)
        self.user_task_model = treemodel.TreeModel(taskrootitem)
        self.user_task_treev.setModel(self.user_task_model)
        tasks = djadapter.tasks.filter(users=user)
        assets = {}
        shots = {}
        atypes = {}
        seqs = {}
        prjs = {}
        for t in tasks:
            tdata = djitemdata.TaskItemData(t)
            titem = treemodel.TreeItem(tdata)
            e = t.element
            if isinstance(e, djadapter.models.Asset):
                eitem = assets.get(e)
                if not eitem:
                    edata = djitemdata.AssetItemData(e)
                    eitem = treemodel.TreeItem(edata)
                    assets[e] = eitem
                egrp = e.atype
                egrpitem = atypes.get(egrp)
                if not egrpitem:
                    egrpdata = djitemdata.AtypeItemData(egrp)
                    egrpitem = treemodel.TreeItem(egrpdata)
                    atypes[egrp] = egrpitem
            else:
                eitem = shots.get(e)
                if not eitem:
                    edata = djitemdata.ShotItemData(e)
                    eitem = treemodel.TreeItem(edata)
                    shots[e] = eitem
                egrp = e.sequence
                egrpitem = seqs.get(egrp)
                if not egrpitem:
                    egrpdata = djitemdata.SequenceItemData(egrp)
                    egrpitem = treemodel.TreeItem(egrpdata)
                    seqs[egrp] = egrpitem
            if eitem not in egrpitem.childItems:
                eitem.set_parent(egrpitem)
            prj = egrp.project
            prjitem = prjs.get(prj)
            if not prjitem:
                prjdata = djitemdata.ProjectItemData(prj)
                prjitem = treemodel.TreeItem(prjdata, taskrootitem)
                prjs[prj] = prjitem
                assetdata = treemodel.ListItemData(["Asset"])
                assetitem = treemodel.TreeItem(assetdata, prjitem)
                shotdata = treemodel.ListItemData(["Shot"])
                shotitem = treemodel.TreeItem(shotdata, prjitem)
            else:
                assetitem = prjitem.child(0)
                shotitem = prjitem.child(1)
            if isinstance(egrp, djadapter.models.Atype) and egrpitem not in assetitem.childItems:
                egrpitem.set_parent(assetitem)
            elif isinstance(egrp, djadapter.models.Sequence) and egrpitem not in shotitem.childItems:
                egrpitem.set_parent(shotitem)
            titem.set_parent(eitem)

        self.cur_user = user
1158145
def get_formset(self, request, obj=None, **kwargs):
        
        FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)
        # Existing objects already got the language code from the queryset().language() method.
        # For new objects, the language code should be set here.
        FormSet.language_code = self.get_form_language(request, obj)

        if self.inline_tabs:
            # Need to pass information to the template, this can only happen via the FormSet object.
            available_languages = self.get_available_languages(obj, FormSet)
            FormSet.language_tabs = self.get_language_tabs(request, obj, available_languages, css_class='parler-inline-language-tabs')
            FormSet.language_tabs.allow_deletion = self._has_translatable_parent_model()   # Views not available otherwise.

        return FormSet
111728
def user_has(ability, get_user=import_user):
    
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            from .models import Ability
            desired_ability = Ability.query.filter_by(
                name=ability).first()
            user_abilities = []
            current_user = get_user()
            for role in current_user._roles:
                user_abilities += role.abilities
            if desired_ability in user_abilities:
                return func(*args, **kwargs)
            else:
                raise Forbidden("You do not have access")
        return inner
    return wrapper
1171738
def form_valid(self, form):
        
        valid = True
        # 'name' is injected in the clean() of the form line 56
        name = form.cleaned_data.get('name').name
        user = self.request.user
        form.save(user=user, service_name=name)

        sa = ServicesActivated.objects.get(name=name)
        if sa.auth_required and sa.self_hosted:
            # trigger the checking of the service
            from django_th.services import default_provider
            default_provider.load_services()
            service_provider = default_provider.get_service(name)
            result = service_provider.check(self.request, user)
            if result is not True:
                # the call of the API failed due to an error which is in the result string
                # return by the call of the API
                form.add_error('host', result)
                messages.error(self.request, result)
                return redirect('edit_service', pk=self.kwargs.get(self.pk_url_kwarg))

        if valid:
            messages.success(self.request, _('Service %s modified successfully') % name.split('Service')[1])
            return HttpResponseRedirect(reverse('user_services'))
1349888
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
                                        ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
                                        extra=3, can_order=False, can_delete=True, min_num=None, max_num=None,
                                        formfield_callback=None, widgets=None, validate_min=False, validate_max=False,
                                        localized_fields=None, labels=None, help_texts=None, error_messages=None,
                                        formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True,
                                        readonly=False):
    
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]

    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': formset,
        'extra': extra,
        'can_delete': can_delete,
        'can_order': can_order,
        'fields': fields,
        'exclude': exclude,
        'max_num': max_num,
        'min_num': min_num,
        'widgets': widgets,
        'validate_min': validate_min,
        'validate_max': validate_max,
        'localized_fields': localized_fields,
        'formreadonlyfield_callback': formreadonlyfield_callback,
        'readonly_fields': readonly_fields,
        'readonly': readonly,
        'labels': labels,
        'help_texts': help_texts,
        'error_messages': error_messages,
    }

    FormSet = smartmodelformset_factory(model, request, **kwargs)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet
370353
def basic_set_of_users_exists_in_the_database(context):
    
    user_model = get_user_model()
    user_model.objects.create(
        username='administrator',
        is_staff=True
    )
    user_model.objects.create(
        username='allowed_user'
    )
    user_model.objects.create(
        username='unallowed_user'
    )
489971
protected function userForm(Fieldset $fieldset, Fluent $model): void
    {
        $fieldset->control('input:email', 'email')
            ->label(\trans('orchestra/foundation::label.users.email'));

        $fieldset->control('password', 'password')
            ->label(\trans('orchestra/foundation::label.users.password'));

        $fieldset->control('text', 'fullname')
            ->label(\trans('orchestra/foundation::label.users.fullname'))
            ->value('Administrator');
    }
667273
def comment_form(context, object):
    
    user = context.get("user")
    form_class = context.get("form", CommentForm)
    form = form_class(obj=object, user=user)
    return form
1268833
def add_user_action_sets(self, _type, name, description, version='v1.0'):
        
        return self._post(
            'user_action_sets/add',
            params={'version': version},
            json=optionaldict(
                type=_type,
                name=name,
                description=description,
                version=version
            ),
            result_processor=lambda x: x['data']['user_action_set_id']
        )
106673
def get_formset(self, request, obj=None, **kwargs):
        
        if obj is not None:
            try:
                # this is enough to load the new schema
                obj.external
            except LayerExternal.DoesNotExist:
                pass
        return super(LayerExternalInline, self).get_formset(request, obj=None, **kwargs)