Python django.contrib.auth.models 模块,User() 实例源码

我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用django.contrib.auth.models.User()

项目:fir_async_plugin    作者:gcrahay    | 项目源码 | 文件源码
def preferences(request):

    class NotificationPreferenceForm(forms.ModelForm):
        event = forms.ChoiceField(choices=registry.get_event_choices(), disabled=True, widget=forms.HiddenInput())
        method = forms.ChoiceField(choices=registry.get_method_choices(), disabled=True, widget=forms.HiddenInput())
        business_lines = forms.ModelMultipleChoiceField(BusinessLine.authorization.for_user(request.user,
                                                                                            'incidents.view_incidents'),
                                                        required=False)

        class Meta:
            fields = "__all__"

    formset = forms.inlineformset_factory(User, NotificationPreference,
                                          formset=NotificationPreferenceFormset,
                                          form=NotificationPreferenceForm)
    if request.method == 'POST':
        fs = formset(request.POST, instance=request.user)
        if fs.is_valid():
            fs.save()
        return redirect('user:profile')
    else:
        fs = formset(instance=request.user)

    return render(request, "fir_async/preferences.html", {'formset': fs})
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def user_login(request):
    """
    Logins user if he passed authentication.
    """
    log_in_form = LogInForm(request.POST)

    if log_in_form.is_valid():
        user = authenticate(username=log_in_form.cleaned_data['username'],
                            password=log_in_form.cleaned_data['passw'])
        if user:
            login(request, user)
            logger.info("User '{}' logged in.".format(user.username))

            return redirect('index')
        else:
            return render(request, 'index.html', {'invalid_authentication': True})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def sort_by_estimation(user, category):
        """
        Sorts books by average count of estimation of each book. Uses aggregate function.

        :param django.contrib.auth.models.User  user:     The request user.
        :param app.models.Category              category: The category.

        :return: The list with sorted books.
        """
        books = []
        filtered_books = Book.exclude_private_books(user, Book.objects.filter(id_category=category))

        for item in filtered_books:
            book_rating = BookRating.objects.filter(id_book=item).aggregate(Avg('rating'))
            book = {'id': item.id,
                    'name': item.book_name,
                    'author': item.id_author.author_name,
                    'url': item.photo.url if item.photo else '',
                    'rating': book_rating['rating__avg']}
            books.append(book)

        return sorted(books, key=lambda info: (info['rating'] is not None, info['rating']), reverse=True)

    # ------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def change_password(request):
    """
    Sets the new password for user.
    """
    if request.is_ajax():
        change_password_form = ChangePasswordForm(request.POST)

        if change_password_form.is_valid():
            with transaction.atomic():

                if request.user.check_password(change_password_form.cleaned_data['prev_password']):
                    request.user.set_password(change_password_form.cleaned_data['new_password'])
                    request.user.save()

                    logger.info("User '{}' changed his password successfully.".format(request.user))

                    changed_password.delay(request.user.username, request.user.email)

                    return HttpResponse(json.dumps('?????? ??????? ???????!'), content_type='application/json')

                else:
                    return HttpResponse(json.dumps('?????? ?????? ?? ?????????. ????????? ?? ??????? ??????.'),
                                        content_type='application/json')
    else:
        return HttpResponse(status=404)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_user_exists(request):
    """
    Checks if user is exists. If exists return True, else False.
    """
    if request.is_ajax():
        is_user_exists_form = IsUserExistsForm(request.GET)

        if is_user_exists_form.is_valid():
            try:
                User.objects.get(username=is_user_exists_form.cleaned_data['username'])
                return HttpResponse(json.dumps(True), content_type='application/json')

            except ObjectDoesNotExist:
                return HttpResponse(json.dumps(False), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def restore_data(request):
    """
    Restores the password for user.
    """
    if request.method == 'POST':
        forgot_form = ForgotPasswordForm(request.POST)

        if forgot_form.is_valid():
            with transaction.atomic():
                temp_password = generate_password()

                user = get_object_or_404(User, email=forgot_form.cleaned_data['email'])
                user.set_password(temp_password)
                user.save()

                restore_account.delay(user.username, temp_password, forgot_form.cleaned_data['email'])

                logger.info("The password for user: '{}' restored successfully.".format(user))

                return HttpResponse(json.dumps(True), content_type='application/json')
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def user_login(request):
    """
    Authenticates user and returns the token which uses to access to the API.
    """
    user = authenticate(username=request.data.get('username'),
                        password=request.data.get('password'))
    if user:
        user_token = TheUser.objects.get(id_user=user).auth_token

        login(request, user)
        logger.info("User '{}' logged in.".format(user.username))

        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'token': user_token}})

    return Response({'status': 404,
                     'detail': 'not authenticated',
                     'data': {'token': None}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_mail_exists(request):
    """
    Checks if mail is exists. If exists return True, else False.
    """
    try:
        User.objects.get(email=request.data.get('email'))
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'email': True}})

    except ObjectDoesNotExist:
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'email': False}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def sign_in(request):
    """
    Creates a new user and returns status.
    """
    with transaction.atomic():
        if 'admin' in request.data.get('username'):
            return Response({'status': 400,
                             'detail': 'not allowed username',
                             'data': {}})

        user = User.objects.create_user(username=request.data.get('username'),
                                        email=request.data.get('email'),
                                        password=request.data.get('passw1'))
        user_token = TheUser.objects.get(id_user=user).auth_token

        logger.info("Created user with name: '{}' mail: '{}' and id: '{}'".format(user.username, user.email, user.id))
        login(request, user)

        successful_registration.delay(user.username, user.email)

        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'token': user_token}})
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def getAnunciosPorSubstring(string):
    safeString = escapeString(string)
    queryString = 'SELECT * FROM anuncio_anuncio WHERE aprovado=1 AND(titulo LIKE \'%' + safeString + '%\' OR descricao LIKE \'%' + safeString + '%\')'
    anuncios = Anuncio.objects.raw(queryString)
    return anuncios


###################################################################################################
#Metodo que retorna anuncios do banco criados por um usuario especifico
#
#Nome: getAnunciosPorUsuario
#Autor: Renan Basilio
#Versao: 1.0
#
#Algoritmo:
#   1. Recupera da tabela de anuncios todos os anuncios e filtra pelo id do usuario fornecido
#
#Utilizacao:
#   getAnunciosPorUsuario(usuario)
#       usuario e um objeto do tipo User do django
#
####################################################################################################
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def getAnunciosPorUsuario(usuario):
    anuncios = Anuncio.objects.all().filter(anunciante=usuario.id)
    return anuncios


###################################################################################################
#Metodo que retorna anuncios do banco com marcados com aprovacao pendente
#
#Nome: getAnunciosPorUsuario
#Autor: Renan Basilio
#Versao: 1.0
#
#Algoritmo:
#   1. Recupera da tabela de anuncios todos os anuncios e filtra pelo id do usuario fornecido
#
#Utilizacao:
#   getAnunciosPorUsuario(usuario)
#       usuario e um objeto do tipo User do django
#
####################################################################################################
项目:minimum-entropy    作者:DistrictDataLabs    | 项目源码 | 文件源码
def test_user_create(self):
        """
        Check that a user can be created using the POST method

        Required to test because the serializer overrides create.
        NOTE: MUST POST IN JSON TO UPDATE/CREATE PROFILE
        """
        endpoint = reverse("api:user-list")
        response = self.client.post(endpoint, data=fixtures['api_user'],
                                    format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # Check that a profile and user exist in database
        user = User.objects.filter(username=fixtures['api_user']['username'])
        profile = Profile.objects.filter(user=user)

        self.assertEquals(len(user), 1)
        self.assertEquals(len(profile), 1)

        self.assertEqual(profile[0].organization, 'SETI')
项目:linkedin_recommend    作者:duggalr2    | 项目源码 | 文件源码
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()


# class ParsedProfile(models.Model):
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     name = models.CharField(max_length=250)
#     header = models.CharField(max_length=500, null=True)
#     url = models.CharField(max_length=500)
#     school = models.CharField(max_length=500, null=True)
#     school_program = models.CharField(max_length=500, null=True)
#
#
# class JobTitle(models.Model):
#     profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE)
#     job = models.CharField(max_length=500, null=True)
#
#
# class Location(models.Model):
#     profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE)
#     loc = models.CharField(max_length=500, default=None)


# Below is All The Profiles that were originally in DB and added new ones by User
# Initial Profiles, only 2000 were in DB (mainly SE/CS focused)
项目:OpsManage    作者:welliamcao    | 项目源码 | 文件源码
def register(request):
    if request.method == "POST":
        if request.POST.get('password') == request.POST.get('c_password'):
            try:
                user = User.objects.filter(username=request.POST.get('username'))
                if len(user)>0:return JsonResponse({"code":500,"data":None,"msg":"????????????"})
                else: 
                    user = User()
                    user.username = request.POST.get('username')
                    user.email = request.POST.get('email')
                    user.is_staff = 0
                    user.is_active = 0
                    user.is_superuser = 0                        
                    user.set_password(request.POST.get('password'))
                    user.save()
                    return JsonResponse({"code":200,"data":None,"msg":"??????"})
            except Exception,e:
                return JsonResponse({"code":500,"data":None,"msg":"??????"}) 
        else:return JsonResponse({"code":500,"data":None,"msg":"?????????????"})
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def owner_search_fields(self):
        """
        Returns all the fields that are CharFields except for password from the
        User model.  For the built-in User model, that means username,
        first_name, last_name, and email.
        """
        try:
            from django.contrib.auth import get_user_model
        except ImportError:  # Django < 1.5
            from django.contrib.auth.models import User
        else:
            User = get_user_model()
        return [
            field.name for field in User._meta.fields
            if isinstance(field, models.CharField) and field.name != 'password'
        ]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def create_assignments(cls, proposal, origin=AUTO_ASSIGNED_INITIAL):
        speakers = [proposal.speaker] + list(proposal.additional_speakers.all())
        reviewers = User.objects.exclude(
            pk__in=[
                speaker.user_id
                for speaker in speakers
                if speaker.user_id is not None
            ]
        ).filter(
            groups__name="reviewers",
        ).filter(
            Q(reviewassignment__opted_out=False) | Q(reviewassignment=None)
        ).annotate(
            num_assignments=models.Count("reviewassignment")
        ).order_by(
            "num_assignments",
        )
        for reviewer in reviewers[:3]:
            cls._default_manager.create(
                proposal=proposal,
                user=reviewer,
                origin=origin,
            )
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def speaker_create_staff(request, pk):
    user = get_object_or_404(User, pk=pk)
    if not request.user.is_staff:
        raise Http404

    try:
        return redirect(user.speaker_profile)
    except ObjectDoesNotExist:
        pass

    if request.method == "POST":
        form = SpeakerForm(request.POST, request.FILES)

        if form.is_valid():
            speaker = form.save(commit=False)
            speaker.user = user
            speaker.save()
            messages.success(request, "Speaker profile created.")
            return redirect("user_list")
    else:
        form = SpeakerForm(initial={"name": user.get_full_name()})

    return render(request, "speakers/speaker_create.html", {
        "form": form,
    })
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _get_storage_model():
    """This configures whether the credentials will be stored in the session
    or the Django ORM based on the settings. By default, the credentials
    will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`
    is found in the settings. Usually, the ORM storage is used to integrate
    credentials into an existing Django user system.

    Returns:
        A tuple containing three strings, or None. If
        ``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple
        will contain the fully qualifed path of the `django.db.model`,
        the name of the ``django.contrib.auth.models.User`` field on the
        model, and the name of the
        :class:`oauth2client.contrib.django_util.models.CredentialsField`
        field on the model. If Django ORM storage is not configured,
        this function returns None.
    """
    storage_model_settings = getattr(django.conf.settings,
                                     'GOOGLE_OAUTH2_STORAGE_MODEL', None)
    if storage_model_settings is not None:
        return (storage_model_settings['model'],
                storage_model_settings['user_property'],
                storage_model_settings['credentials_property'])
    else:
        return None, None, None
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def alter_profile(request, username=None):
    if username:
        the_user = get_object_or_404(User, username__exact=username)
    else:
        the_user = request.user
    if request.method == 'POST':
        redirect_url = reverse("view-profile-user", args=[the_user.username])
        form = UserAlterDetailsForm(request.POST)
        if "cancel" in form.data:  # has to be tested before data is cleaned
            return HttpResponseRedirect(redirect_url)
        assert form.is_valid()
        if form.is_valid():
            for key in form.cleaned_data:
                setattr(the_user, key, form.cleaned_data[key])
            the_user.save()
            msg = "Profile details changed"
            messages.add_message(request, messages.INFO, msg)
            return HttpResponseRedirect(redirect_url)
    else:
        # form = UserAlterDetailsForm(initial=the_user.__dict__)
        form = UserAlterDetailsForm(instance=the_user)
    return render_template(request, "profiles/alter_profile.html",
                           {"the_user": the_user,
                            "form": form})
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_get_token_key(self):
        client = Client()
        request_url = "/api/v1/token-auth"
        username = "parent1"
        password = "123123"
        user = authenticate(username=username, password=password)
        self.assertNotEqual(user, None)
        parent_user = User.objects.get(username=username)
        self.assertEqual(parent_user.is_active, 1)
        response = client.post(request_url, {"username": username,
                                             "password": password})
        self.assertEqual(response.status_code, 200)

        client2 = Client()
        response2 = client2.post(request_url, {"username": username,
                                               "password": password})
        self.assertEqual(response.content, response2.content)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_modify_avatar_by_teacher(self):
        # Teacher role not allowed to modify avatar.
        username = "test1"
        password = "123123"
        user = User.objects.get(username=username)

        change_profile_perm = Permission.objects.get(name='Can change profile')
        user.user_permissions.add(change_profile_perm)
        user.save()

        client = Client()
        client.login(username=username, password=password)
        request_url = "/api/v1/profiles/%d" % (user.profile.pk,)
        img_name = 'img0'  # NOTE: seq is 0 not 1, seq of the user 'parent1'
        img_path = os.path.join(
                app_path, 'migrations', 'avatars', img_name + '.jpg')
        # print(img_path)
        img_fd = open(img_path, 'rb')
        data = {'avatar': img_fd}
        encoded_data = encode_multipart(BOUNDARY, data)
        response = client.patch(request_url, content_type=MULTIPART_CONTENT,
                                data=encoded_data)
        self.assertEqual(409, response.status_code)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def new_student() -> User:
        # ????
        username = random_string()[:30]
        salt = random_string()[:5]
        password = "malalaoshi"
        user = User(username=username)
        user.email = ""
        user.password = make_password(password, salt)
        user.save()
        student_group = Group.objects.get(name="??")
        user.groups.add(student_group)
        # ??????
        profile = Profile(user=user)
        profile.save()
        student = Student(user=user)
        student.save()
        # ????
        user.save()
        profile.save()
        student.save()
        ret_user = authenticate(username=username, password=password)
        return ret_user
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def new_parent()->User:
        # ????
        username = random_string()[:30]
        salt = random_string()[:5]
        password = "malalaoshi"
        user = User(username=username)
        user.email = ""
        user.password = make_password(password, salt)
        user.save()
        parent_group = Group.objects.get(name="??")
        user.groups.add(parent_group)
        # ??????
        profile = Profile(user=user)
        profile.save()
        parent = Parent(user=user)
        parent.save()
        # ????
        user.save()
        profile.save()
        parent.save()
        ret_user = authenticate(username=username, password=password)
        return ret_user
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def information_complete_percent(user: User):
    """
    ?????????
    :param user:
    :return:
    """
    total = 4
    unfinished = 0
    Teacher = models.Teacher
    Profile = models.Profile
    teacher = Teacher.objects.get(user=user)
    profile = Profile.objects.get(user=user)
    if teacher.name == "":
        unfinished += 1
    if profile.gender == "u":
        unfinished += 1
    if teacher.region is None:
        unfinished += 1
    if len(teacher.abilities.all()) == 0:
        unfinished += 1
    return (total - unfinished) / total


# ????????? TW-2-1
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def setUp(self):
        super().setUp()
        self.proposal = mixer.blend(Proposal)
        self.user = mixer.blend(User)
        mixer.blend(Profile, user=self.user)
        self.client.force_login(self.user)
        self.semester = mixer.blend(
            Semester, id='2016B', start=datetime(2016, 9, 1, tzinfo=timezone.utc),
            end=datetime(2016, 12, 31, tzinfo=timezone.utc)
        )
        self.time_allocation_1m0_sbig = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=self.semester,
            telescope_class='1m0', instrument_name='1M0-SCICAM-SBIG', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10, too_time_used=0.0, ipp_limit=10.0, ipp_time_available=5.0
        )

        self.time_allocation_2m0_floyds = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=self.semester,
            telescope_class='2m0', instrument_name='2M0-FLOYDS-SCICAM', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10, too_time_used=0.0, ipp_limit=10.0, ipp_time_available=5.0
        )

        self.membership = mixer.blend(Membership, user=self.user, proposal=self.proposal)
        self.generic_payload = copy.deepcopy(generic_payload)
        self.generic_payload['proposal'] = self.proposal.id
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def setUp(self):
        super().setUp()
        self.proposal = mixer.blend(Proposal)
        self.user = mixer.blend(User)
        self.client.force_login(self.user)

        mixer.blend(Membership, user=self.user, proposal=self.proposal)

        semester = mixer.blend(
            Semester,
            id='2016B',
            start=datetime(2016, 9, 1, tzinfo=timezone.utc),
            end=datetime(2016, 12, 31, tzinfo=timezone.utc),
        )

        self.time_allocation_1m0 = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=semester,
            telescope_class='1m0', instrument_name='1M0-SCICAM-SBIG', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10, too_time_used=0.0, ipp_limit=10.0, ipp_time_available=5.0
        )

        self.generic_payload = copy.deepcopy(generic_payload)
        self.generic_payload['ipp_value'] = 1.5
        self.generic_payload['proposal'] = self.proposal.id
        self.generic_payload['group_id'] = 'ipp_request'
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def setUp(self):
        super().setUp()
        self.proposal = mixer.blend(Proposal)
        self.user = mixer.blend(User)
        self.client.force_login(self.user)

        mixer.blend(Membership, user=self.user, proposal=self.proposal)

        semester = mixer.blend(
            Semester,
            id='2016B',
            start=datetime(2016, 9, 1, tzinfo=timezone.utc),
            end=datetime(2016, 12, 31, tzinfo=timezone.utc),
        )

        self.time_allocation_1m0 = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=semester,
            telescope_class='1m0', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10, too_time_used=0.0, ipp_limit=10.0,
            ipp_time_available=5.0
        )
        self.generic_payload = copy.deepcopy(generic_payload)
        self.generic_payload['proposal'] = self.proposal.id
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def setUp(self):
        super().setUp()
        self.proposal = mixer.blend(Proposal)
        self.user = mixer.blend(User)
        self.client.force_login(self.user)

        semester = mixer.blend(Semester, id='2016B', start=datetime(2016, 9, 1, tzinfo=timezone.utc),
                               end=datetime(2016, 12, 31, tzinfo=timezone.utc))

        self.time_allocation_1m0 = mixer.blend(TimeAllocation, proposal=self.proposal, semester=semester,
                                               telescope_class='1m0', std_allocation=100.0, std_time_used=0.0,
                                               too_allocation=10, too_time_used=0.0, ipp_limit=10.0,
                                               ipp_time_available=5.0, instrument_name='1M0-SCICAM-SBIG')
        self.time_allocation_2m0 = mixer.blend(TimeAllocation, proposal=self.proposal, semester=semester,
                                               telescope_class='2m0', std_allocation=100.0, std_time_used=0.0,
                                               too_allocation=10, too_time_used=0.0, ipp_limit=10.0,
                                               ipp_time_available=5.0, instrument_name='2M0-FLOYDS-SCICAM')

        mixer.blend(Membership, user=self.user, proposal=self.proposal)
        self.generic_payload = copy.deepcopy(generic_payload)
        self.generic_payload['proposal'] = self.proposal.id
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def setUp(self):
        super().setUp()
        self.proposal = mixer.blend(Proposal, id='temp')
        self.semester = mixer.blend(Semester, id='2016B', start=datetime(2016, 9, 1, tzinfo=timezone.utc),
                                    end=datetime(2016, 12, 31, tzinfo=timezone.utc))

        self.time_allocation_1m0_sbig = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=self.semester, telescope_class='1m0',
            instrument_name='1M0-SCICAM-SBIG', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10.0, too_time_used=0.0, ipp_limit=10.0, ipp_time_available=1.0
        )
        self.time_allocation_0m4_sbig = mixer.blend(
            TimeAllocation, proposal=self.proposal, semester=self.semester, telescope_class='0m4',
            instrument_name='0M4-SCICAM-SBIG', std_allocation=100.0, std_time_used=0.0,
            too_allocation=10.0, too_time_used=0.0, ipp_limit=10.0, ipp_time_available=1.0
        )
        self.user = mixer.blend(User)
        mixer.blend(Membership, user=self.user, proposal=self.proposal)
        self.client.force_login(self.user)
        self.generic_payload = copy.deepcopy(generic_payload)
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def add_users(self, emails, role):
        for email in emails:
            if User.objects.filter(email=email).exists():
                membership, created = Membership.objects.get_or_create(
                    proposal=self,
                    user=User.objects.get(email=email),
                    role=role
                )
                if created:
                    membership.send_notification()
            else:
                proposal_invite, created = ProposalInvite.objects.get_or_create(
                    proposal=self,
                    role=role,
                    email=email
                )
                proposal_invite.send_invitation()

        logger.info('Users added to proposal {0}: {1}'.format(self, emails))
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def response_add(self, request, obj, post_url_continue=None):
        """
        Determines the HttpResponse for the add_view stage. It mostly defers to
        its superclass implementation but is customized because the User model
        has a slightly different workflow.
        """
        # We should allow further modification of the user just added i.e. the
        # 'Save' button should behave like the 'Save and continue editing'
        # button except in two scenarios:
        # * The user has pressed the 'Save and add another' button
        # * We are adding a user in a popup
        if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST:
            request.POST = request.POST.copy()
            request.POST['_continue'] = 1
        return super(UserAdmin, self).response_add(request, obj,
                                                   post_url_continue)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def set_course_run_to_past_graded(user, course_run, grade, upgradeable=False, now=None):
    """Ensures that a CourseRun is in the past and has an associated final grade for a given User"""
    if not course_run.is_past:
        set_course_run_past(course_run, upgradeable=upgradeable, save=True)
    elif upgradeable and not course_run.is_upgradable:
        course_run.upgrade_deadline = now + timedelta(days=15)
        course_run.save()
    elif not upgradeable and course_run.is_upgradable:
        course_run.upgrade_deadline = course_run.enrollment_end
        course_run.save()
    # Create enrollment if it doesn't exist
    CachedEnrollmentHandler(user).set_or_create(course_run)
    # Create final grade
    final_grade_defaults = dict(
        grade=grade,
        passed=grade >= PASSING_GRADE,
        status=FinalGradeStatus.COMPLETE
    )
    FinalGrade.objects.update_or_create(
        user=user,
        course_run=course_run,
        defaults=final_grade_defaults
    )
    return course_run
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def deserialize_user_data(user_data, programs):
    """
    Deserializes a dict of mixed User/Profile data and returns the newly-inserted User
    """
    username = FAKE_USER_USERNAME_PREFIX + user_data['email'].split('@')[0]
    user = deserialize_model_data(User, user_data, username=username)
    # Create social username
    user.social_auth.create(
        provider=EdxOrgOAuth2.name,
        uid=user.username,
    )
    # The user data is generated in this script with mute_signals(post_save)
    # so we need to create the profile explicitly.
    profile = deserialize_model_data(Profile, user_data, user=user, fake_user=True)
    deserialize_profile_detail_data(profile, Employment, user_data['work_history'])
    deserialize_profile_detail_data(profile, Education, user_data['education'])
    deserialize_dashboard_data(user, user_data, programs)
    ensure_cached_data_freshness(user)
    return user
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def profile(request, profile_id):
    """
    Renders the profile page.
    """
    if request.method == 'GET':
        if request.user.is_authenticated():
            user = get_object_or_404(User, id=profile_id)
            profile_user = get_object_or_404(TheUser, id_user=user)

            added_books = AddedBook.objects.filter(id_user=profile_user)
            uploaded_books = Book.objects.filter(who_added=profile_user).order_by('-id')

            context = {'profile_user': profile_user, 'added_books': added_books, 'uploaded_books': uploaded_books}

            if request.user.username == profile_user.id_user.username:
                context['owner'] = True

            return render(request, 'profile.html', context)

        else:
            return redirect('index')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def upload_avatar(request):
    """
    Sets new user's avatar.
    """
    if request.is_ajax():
        upload_avatar_form = UploadAvatarForm(request.POST, request.FILES)

        with transaction.atomic():
            user = get_object_or_404(User, id=request.user.id)
            profile_user = get_object_or_404(TheUser, id_user=user)

            if upload_avatar_form.is_valid():
                profile_user.user_photo.save('user_{}.png'.format(profile_user.id),
                                             upload_avatar_form.cleaned_data['avatar'])
                profile_user.save()
                logger.info("User '{}' changed his avatar.".format(profile_user))

                resize_image(profile_user.user_photo.path, AVATAR_WIDTH)
                logger.info("Image '{}' successfully resized!".format(profile_user.user_photo.path))

                response_data = {'message': '?????? ??????? ???????!'}
                return HttpResponse(json.dumps(response_data), content_type='application/json')

            else:
                logger.info("User '{}' tried to upload not an image as avatar!".format(profile_user))
                return HttpResponse(json.dumps(False), content_type='application/json', status=500)

    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def sign_in(request):
    """
    Creates a new user and returns page with registration status.
    """
    if request.method == 'POST':
        sign_in_form = SignInForm(request.POST)

        if sign_in_form.is_valid():
            re_captcha_response = request.POST.get('g-recaptcha-response', '')

            if validate_captcha(re_captcha_response):
                with transaction.atomic():
                    user = User.objects.create_user(username=sign_in_form.cleaned_data['username'],
                                                    email=sign_in_form.cleaned_data['email'],
                                                    password=sign_in_form.cleaned_data['passw1'])

                    logger.info("Created user with name: '{}' mail: '{}' and id: '{}'"
                                .format(user.username, user.email, user.id))
                    login(request, user)

                    successful_registration.delay(user.username, user.email)

            return redirect('/')


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def create_additional_data(sender, instance=None, created=False, **kwargs):
    """
    Creates '.models.TheUser' instance and auth_token for this instance after creating User instance.
    """
    if created:
        the_user = TheUser.objects.create(id_user=instance,
                                          auth_token=uuid.uuid5(uuid.NAMESPACE_DNS, instance.username))
        the_user.save()


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def remove_user_obj(sender, instance=None, **kwargs):
    """
    Removes standard django User model if '.models.TheUser' instance was deleted.
    """
    user = instance.id_user
    user.delete()
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def sort_by_book_name(user, category):
        """
        Sorts books by book name.

        :param django.contrib.auth.models.User  user:     The request user.
        :param app.models.Category              category: The category.

        :return list[dict[str, str]]: list of books with data.
        """
        books = Book.objects.filter(id_category=category).order_by('book_name')
        filtered_books = Book.exclude_private_books(user, books)

        return Book.generate_books(filtered_books)

    # ------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def sort_by_readable(user, category=None):
        """
        Sorts books by most readable criterion. Uses aggregate 'count' function.

        :param django.contrib.auth.models.User  user:     The request user.
        :param app.models.Category              category: The category.

        :return: The list with sorted books.
        """
        books = []
        if category:
            filtered_books = Book.exclude_private_books(user, Book.objects.filter(id_category=category))
        else:
            filtered_books = Book.exclude_private_books(user, Book.objects.all())

        for item in filtered_books:
            book_read_count = AddedBook.objects.filter(id_book=item).aggregate(Count('id_user'))
            book = {'id': item.id,
                    'name': item.book_name,
                    'author': item.id_author.author_name,
                    'url': item.photo.url if item.photo else '',
                    'read_count': book_read_count['id_user__count']}
            books.append(book)

        return sorted(books, key=lambda info: info['read_count'], reverse=True)

    # ------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def exclude_private_books(user, books):
        """
        Returns the list of books without private books which not depend to current user

        :param django.contrib.auth.models.User               user:         The request user.
        :param django.db.models.query.QuerySet[.models.Book] books:        The given list of books.

        :return list[.models.Book]: List of books.
        """
        if user.is_anonymous:
            the_user = user
        else:
            the_user = TheUser.objects.get(id_user=user)

        filtered_books = []

        for book in books:
            if book.private_book and book.who_added != the_user:
                continue

            filtered_books.append(book)

        return filtered_books


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def restore_data(request):
    """
    Sends mail to restore user data.
    """
    with transaction.atomic():
        temp_password = generate_password()

        try:
            user = User.objects.get(email=request.data.get('email'))
            user.set_password(temp_password)
            user.save()

            restore_account.delay(user.username, temp_password, request.data.get('email'))

            logger.info("The password for user: '{}' restored successfully.".format(user))

            return Response({'status': 200,
                             'detail': 'successful',
                             'data': {}})

        except ObjectDoesNotExist:
            return Response({'status': 404,
                             'detail': 'not exists',
                             'data': {}})


# ----------------------------------------------------------------------------------------------------------------------