A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`
    :param user: a :py:class:`django.contrib.auth.models.User` instance
359640
def user_preference_form_builder(instance, preferences=[], **kwargs):
    
    return preference_form_builder(
        UserPreferenceForm,
        preferences,
        model={'instance': instance},
        **kwargs)
1085391
def preferences_class_prepared(sender, *args, **kwargs):
    
    cls = sender
    if issubclass(cls, Preferences):
        # Add singleton manager to subclasses.
        cls.add_to_class('singleton', SingletonManager())
        # Add property for preferences object to preferences.preferences.
        setattr(preferences.Preferences, cls._meta.object_name, property(lambda x: cls.singleton.get()))
691617
def set_user_preferences_from_request(request):
    
    prefs = []

    for pref in request.POST.getlist(_PREF_POST_KEY):
        message_alias, messenger_alias = pref.split(_ALIAS_SEP)

        try:
            get_registered_message_type(message_alias)
            get_registered_messenger_object(messenger_alias)

        except (UnknownMessengerError, UnknownMessageTypeError):
            pass

        else:
            prefs.append((message_alias, messenger_alias))

    Subscription.replace_for_user(request.user, prefs)

    return bool(prefs)
573304
private function _init_user(bbn\user $user): preferences
  {
    $this->user = $user;
    $this->id_user = $this->user->get_id();
    $this->id_group = $this->user->get_group();
    return $this;
  }
152923
def prj_create_user(self, *args, **kwargs):
        
        if not self.cur_prj:
            return
        user = self.create_user(projects=[self.cur_prj])
        if user:
            userdata = djitemdata.UserItemData(user)
            treemodel.TreeItem(userdata, self.prj_user_model.root)
48876
def POST(self, *args, **kwargs):
        
        if self.user_manager.session_logged_in():
            if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage":
                raise web.seeother("/preferences/profile")

            if not self.is_lti_page and self.user_manager.session_lti_info() is not None:  # lti session
                self.user_manager.disconnect_user()
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods_fields(), False)

            return self.POST_AUTH(*args, **kwargs)
        else:
            user_input = web.input()
            if "login" in user_input and "password" in user_input:
                if self.user_manager.auth_user(user_input["login"].strip(), user_input["password"]) is not None:
                    return self.GET_AUTH(*args, **kwargs)
                else:
                    return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), True)
            else:
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
1236772
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """"""
        defaults = {
            'form_class': form_class or self.get_form_class()
        }
        defaults.update(kwargs)

        return super(ListField, self).formfield(**defaults)
1346055
def create_deletion_handler(preference):
    
    def delete_related_preferences(sender, instance, *args, **kwargs):
        queryset = preference.registry.preference_model.objects\
                                      .filter(name=preference.name,
                                              section=preference.section)
        related_preferences = queryset.filter(
            raw_value=preference.serializer.serialize(instance))
        related_preferences.delete()
    return delete_related_preferences
169918
def task_add_user(self, *args, **kwargs):
        
        if not self.cur_task:
            return

        dialog = UserAdderDialog(task=self.cur_task)
        dialog.exec_()
        users = dialog.users
        for user in users:
            userdata = djitemdata.UserItemData(user)
            treemodel.TreeItem(userdata, self.task_user_model.root)
1369673
def create_user(username, password=None, email=None, first_name="", last_name="",
                role="MEMBER", login_method=None):
    

    if not login_method:
        login_method = "email" if "@" in username else "username"

    def cb():
        return _user(models.AuthUser.new(username=username,
                                         password=password,
                                         email=email,
                                         first_name=first_name,
                                         last_name=last_name,
                                         login_method=login_method,
                                         role=role))

    return signals.create_user(cb)
455514
def user_default_serializer(self, obj):
        """"""
        if not obj:
            return None
        self.user_default_add_related_pks(obj)
        return dict((
            ('id', obj.id),
            ('username', obj.username),
            self.field_to_json('DateTime', 'date_joined', obj.date_joined),
            self.field_to_json(
                'PKList', 'votes', model=Choice, pks=obj._votes_pks),
        ))
627162
def preferences_view(request, semester, targetUsername, profile=None):
    
    # TODO: Change template to show descriptions in tooltip / ajax show box?
    wprofile = get_object_or_404(
        WorkshiftProfile,
        user__username=targetUsername,
    )
    full_management = utils.can_manage(request.user, semester=semester)

    if wprofile.user != request.user and \
       not full_management:
        messages.add_message(
            request,
            messages.ERROR,
            MESSAGES["ADMINS_ONLY"],
        )
        return HttpResponseRedirect(semester.get_view_url())

    rating_forms = []
    for wtype in WorkshiftType.objects.filter(rateable=True):
        try:
            rating = wprofile.ratings.get(workshift_type=wtype)
        except WorkshiftRating.DoesNotExist:
            rating = WorkshiftRating(workshift_type=wtype)
        form = WorkshiftRatingForm(
            data=request.POST or None,
            prefix="rating-{}".format(wtype.pk),
            instance=rating,
            profile=wprofile,
        )
        rating_forms.append(form)

    time_formset = TimeBlockFormSet(
        data=request.POST or None,
        prefix="time",
        profile=wprofile,
    )
    note_form = ProfileNoteForm(
        data=request.POST or None,
        instance=wprofile,
        prefix="note",
    )

    if all(i.is_valid() for i in rating_forms) and time_formset.is_valid() and \
       note_form.is_valid():
        for form in rating_forms:
            form.save()
        time_formset.save()
        note_form.save()
        if wprofile.preference_save_time is None:
            wprofile.preference_save_time = now()
            wprofile.save()
        messages.add_message(
            request,
            messages.INFO,
            "Preferences saved.",
        )
        return HttpResponseRedirect(wurl(
            "workshift:preferences",
            sem_url=semester.sem_url,
            targetUsername=request.user.username,
        ))

    if wprofile == profile:
        page_name = "My Workshift Preferences"
    else:
        page_name = "{}'s Workshift Preferences".format(
            wprofile.user.get_full_name(),
        )
    return render_to_response("preferences.html", {
        "page_name": page_name,
        "profile": wprofile,
        "rating_forms": rating_forms,
        "time_formset": time_formset,
        "note_form": note_form,
    }, context_instance=RequestContext(request))
584554
def create_settings(sender, **kwargs):
    
    created = kwargs['created']
    user = kwargs['instance']
    if created:
        UserWebNotificationSettings.objects.create(user=user)
        UserEmailNotificationSettings.objects.create(user=user)
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())
198127
def createuser(ctx, email, password, superuser, no_password, prompt):
    ''

    if prompt:
        if not email:
            email = click.prompt('Email')

        if not (password or no_password):
            password = click.prompt('Password')

        if superuser is None:
            superuser = click.confirm('Should this user be a superuser?', default=False)

    if superuser is None:
        superuser = False

    if not email:
        raise click.ClickException('Invalid or missing email address.')

    if not no_password and not password:
        raise click.ClickException('No password set and --no-password not passed.')

    import django
    django.setup()

    from bitcaster.models import User

    user = User.objects.filter(email=email).first()

    if user:
        if prompt:
            change = click.confirm(f'User {email} already exists. Proceed updating it?', default=False)
            if not change:
                ctx.exit()
            user.set_password(password)
            if superuser:
                user.is_superuser = superuser

            op = 'updated'
        else:
            click.echo('Nothing to do. User exists', err=True, color='red')
            sys.exit(1)
    else:
        op = 'created'
        user = User(
            email=email,
            is_superuser=superuser,
            is_staff=superuser,
            is_active=True,
        )
        if password:
            user.set_password(password)

    try:
        user.save()
    except Exception as e:
        raise click.ClickException(e)

    click.echo(f'User {email} {op}')
665988
def update_password_from_form(self, user=None, form=None):
        
        user = user or self.current
        if not form and "form" in current_context.data and request.method == "POST":
            form = current_context.data.form
        elif not form:
            raise OptionMissingError("Missing a form in 'update_user_password' action")

        self._update_password_from_form(user, form)
        save_model(user)
        self.update_user_password_signal.send(self, user=user)
842922
public function scopeOfUser(Builder $builder, Model $user): Builder
    {
        return $builder->where('user_type', $user->getMorphClass())->where('user_id', $user->getKey());
    }