Convert a lazy user to a non-lazy one. The form passed
        in is expected to be a ModelForm instance, bound to the user
        to be converted.

        The converted ``User`` object is returned.

        Raises a TypeError if the user is not lazy.
356635
def convert(self, form):
        
        if not is_lazy_user(form.instance):
            raise NotLazyError('You cannot convert a non-lazy user')

        user = form.save()

        # We need to remove the LazyUser instance assocated with the
        # newly-converted user
        self.filter(user=user).delete()
        converted.send(self, user=user)
        return user
735635
def to_user(user):
        
        from sevenbridges.models.user import User
        if not user:
            raise SbgError('User is required!')
        elif isinstance(user, User):
            return user.username
        elif isinstance(user, six.string_types):
            return user
        else:
            raise SbgError('Invalid user parameter!')
1287489
def convert(request, form_class=None,
            redirect_field_name='redirect_to',
            anonymous_redirect=settings.LOGIN_URL,
            template_name='lazysignup/convert.html',
            ajax_template_name='lazysignup/convert_ajax.html'):
    
    redirect_to = 'lazysignup_convert_done'

    if form_class is None:
        if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
            form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
        else:
            form_class = UserCreationForm

    # If we've got an anonymous user, redirect to login
    if request.user.is_anonymous:
        return HttpResponseRedirect(anonymous_redirect)

    if request.method == 'POST':
        redirect_to = request.POST.get(redirect_field_name) or redirect_to
        form = form_class(request.POST, instance=request.user)
        if form.is_valid():
            try:
                LazyUser.objects.convert(form)
            except NotLazyError:
                # If the user already has a usable password, return a Bad
                # Request to an Ajax client, or just redirect back for a
                # regular client.
                if request.is_ajax():
                    return HttpResponseBadRequest(
                        content=_(u"Already converted."))
                else:
                    return redirect(redirect_to)

            # Re-log the user in, as they'll now not be authenticatable with
            # the Lazy backend
            login(request, authenticate(**form.get_credentials()))

            # If we're being called via AJAX, then we just return a 200
            # directly to the client. If not, then we redirect to a
            # confirmation page or to redirect_to, if it's set.
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(redirect_to)

        # Invalid form, now check to see if is an ajax call
        if request.is_ajax():
            return HttpResponseBadRequest(content=str(form.errors))
    else:
        form = form_class()

    # If this is an ajax request, prepend the ajax template to the list of
    # templates to be searched.
    if request.is_ajax():
        template_name = [ajax_template_name, template_name]
    return render(
        request,
        template_name,
        {
            'form': form,
            'redirect_to': redirect_to
        },
    )
195044
def instance_from_url(url, user=None):
    
    # XXX: This circular dependency will be removed then filter_queryset_for_user
    # will be moved to model manager method
    from waldur_core.structure.managers import filter_queryset_for_user

    url = clear_url(url)
    match = resolve(url)
    model = get_model_from_resolve_match(match)
    queryset = model.objects.all()
    if user is not None:
        queryset = filter_queryset_for_user(model.objects.all(), user)
    return queryset.get(**match.kwargs)
359640
def user_preference_form_builder(instance, preferences=[], **kwargs):
    
    return preference_form_builder(
        UserPreferenceForm,
        preferences,
        model={'instance': instance},
        **kwargs)
329337
def username_matches_request_user(view_fn):
    
    @wraps(view_fn)
    def wrapper(request, username, *args, **kwargs):
        User = get_user_model()

        user = get_object_or_404(User, username=username)
        if user != request.user:
            return HttpResponseForbidden()
        else:
            return view_fn(request, user, *args, **kwargs)

    return wrapper
259288
def get_form(self, form_class):
        """"""
        if not hasattr(self, '_form'):
            kwargs = self.get_form_kwargs()
            self._form = form_class(instance=self.object, **kwargs)
        return self._form
1235309
def get_user(self, username):
        
        User = get_user_model()
        try:
            user = User.objects.get(**{
                User.USERNAME_FIELD: username,
            })
            if user.is_active:
                raise ActivationError(
                    self.ALREADY_ACTIVATED_MESSAGE,
                    code='already_activated'
                )
            return user
        except User.DoesNotExist:
            raise ActivationError(
                self.BAD_USERNAME_MESSAGE,
                code='bad_username'
            )
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 '/')
890687
def get_form(self):
        
        self.form = super(SmartFormMixin, self).get_form()

        fields = list(self.derive_fields())

        # apply our field filtering on our form class
        exclude = self.derive_exclude()
        exclude += self.derive_readonly()

        # remove any excluded fields
        for field in exclude:
            if field in self.form.fields:
                del self.form.fields[field]

        if fields is not None:
            # filter out our form fields
            remove = [name for name in self.form.fields.keys() if name not in fields]
            for name in remove:
                del self.form.fields[name]

        # stuff in our referer as the default location for where to return
        location = forms.CharField(widget=forms.widgets.HiddenInput(), required=False)

        if ('HTTP_REFERER' in self.request.META):
            location.initial = self.request.META['HTTP_REFERER']

        # add the location to our form fields
        self.form.fields['loc'] = location

        if fields:
            fields.append('loc')

        # provides a hook to programmatically customize fields before rendering
        for (name, field) in self.form.fields.items():
            field = self.customize_form_field(name, field)
            self.form.fields[name] = field

        return self.form
1055851
def form(cls, name, type_=Type.String, description=None, required=None, default=None,
             minimum=None, maximum=None, enum=None, **options):
        
        if minimum is not None and maximum is not None and minimum > maximum:
            raise ValueError("Minimum must be less than or equal to the maximum.")
        return cls(name, In.Form, type_, None, description,
                   required=required, default=default,
                   minimum=minimum, maximum=maximum,
                   enum=enum, **options)
431791
def save(self):
        
        # First save the parent form and get the user.
        new_user = super(SignupFormExtra, self).save()

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.save()

        # Userena expects to get the new user from this form, so return the new
        # user.
        return new_user
1329384
def form_invalid(self, form):
        
        meta = getattr(self.model, '_meta')

        #noinspection PyUnresolvedReferences
        messages.error(
            self.request,
            _(u'The {0} could not be saved due to errors.').format(
                meta.verbose_name.lower()
            )
        )

        return super(BaseEditView, self).form_invalid(form)
1047883
def clean_form_template(self):
        
        form_template = self.cleaned_data.get('form_template', '')
        if form_template:
            try:
                get_template(form_template)
            except TemplateDoesNotExist:
                msg = _('Selected Form Template does not exist.')
                raise forms.ValidationError(msg)
        return form_template
1302240
def user(self, user):
        
        if user is None:
            raise ValueError("Invalid value for `user`, must not be `None`")
        if user is not None and len(user) > 1024:
            raise ValueError("Invalid value for `user`, length must be less than or equal to `1024`")

        self._user = user
522119
def get_django_user(self, username, password=None):
        
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)

        if password is not None:
            user.set_password(password)
            user.save()

        return user
104767
def get_form(self, key, form_class=None):
        
        if form_class is None:
            form_class = self.get_form_class(key)
        return form_class(**self.get_form_kwargs(key))