django.contrib.auth.models.User.objects.filter.first - python examples

Here are the examples of the python api django.contrib.auth.models.User.objects.filter.first taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

49 Examples 7

3 View Complete Implementation : helpers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : anexia-it
    def django_check_login(self, username, pastword):
        """
        Checks the django login by querying the user from the database and calling check_pastword()
        :param username:
        :param pastword:
        :return:
        """
        user = User.objects.filter(username=username).first()

        return user.check_pastword(pastword)

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_all_results_for_org_who_cant_transfer(self):
        user = User.objects.filter(
            profile__organization__county__slug='solano').first()
        with self.astertNumQueries(6):
            results = AppsService.get_all_applications_for_org_user(user, 1)
        self.astertTrue(results.object_list)
        for thing in results:
            self.astertTrue(isinstance(thing, OrderedDict))

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_all_results_for_org_who_can_transfer(self):
        user = User.objects.filter(
            profile__organization__county__slug='alameda').first()
        with self.astertNumQueries(7):
            results = AppsService.get_all_applications_for_org_user(user, 1)
        self.astertTrue(results.object_list)
        for thing in results:
            self.astertTrue(isinstance(thing, OrderedDict))
            self.astertIn('incoming_transfers', thing)

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_all_results_for_org_who_has_outgoing_transfers(self):
        user = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        to_org = Organization.objects.get(slug='ebclc')
        application = models.Application.objects.filter(
            organization__county__slug='alameda').first()
        TransferService.transfer_application(
            user, application, to_org, 'food replicator malfunction')
        with self.astertNumQueries(5):
            results = AppsService.get_all_applications_for_org_user(user, 1)
        self.astertTrue(
            any([
                app['was_transferred_out'] for app in results
            ]))

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_all_results_are_in_proper_order(self):
        user = User.objects.filter(
            profile__organization__slug='cc_pubdef').first()
        results = AppsService.get_all_applications_for_org_user(user, 1)
        future = timezone.now() + timedelta(days=10000)
        for item in results:
            date = item['form_submission']['local_date_received']
            self.astertTrue(date <= future)
            future = date

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_unread_results_only_include_unreads(self):
        user = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        results = AppsService.get_unread_applications_for_org_user(user, 1)
        self.astertFalse(
            any([
                app['has_been_opened'] for app in results
            ]))

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_needs_updates_results_only_include_apps_needing_update(self):
        user = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        results = AppsService.get_applications_needing_updates_for_org_user(
            user, 1)
        self.astertFalse(
            any([
                app['status_updates'] for app in results
            ]))

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def all_results_include_unread_apps(self):
        user = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        results = AppsService.get_all_applications_for_org_user(user, 1)
        self.astertTrue(
            any([
                app['has_been_opened'] for app in results
            ]))

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_number_of_queries_for_no_transfers(self):
        application = models.Application.objects.filter(
            organization__slug='a_pubdef').first()
        author = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        # make more status updates
        new_updates_count = random.randint(1, 7)
        for i in range(new_updates_count):
            factories.StatusUpdateFactory.create(
                application=application, author=author)
        with self.astertNumQueriesLessThanEqual(9):
            AppsService.get_serialized_application_history_events(
                application, author)

3 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_number_of_queries_if_transferred_in(self):
        author = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        application = models.Application.objects.filter(
            organization__slug='a_pubdef').first()
        to_org = Organization.objects.get(slug='ebclc')
        receiving_user = User.objects.filter(
            profile__organization__slug='ebclc').first()
        transfer, *other = TransferService.transfer_application(
            author, application, to_org, 'holodeck malfunction')
        app = transfer.new_application
        new_updates_count = random.randint(1, 7)
        for i in range(new_updates_count):
            factories.StatusUpdateFactory.create(
                application=app, author=receiving_user)
        with self.astertNumQueriesLessThanEqual(14):
            AppsService.get_serialized_application_history_events(
                application, receiving_user)

3 View Complete Implementation : test_transfers_service.py
Copyright MIT License
Author : codeforamerica
    def test_expected_number_of_queries(self):
        user = User.objects.filter(
            profile__organization__county__slug='alameda').first()
        to_org = Organization.objects.get(slug='ebclc')
        application = models.Application.objects.filter(
            organization__slug='a_pubdef').first()
        with self.astertNumQueries(19):
            TransferService.transfer_application(
                user, application, to_org, 'there was a temporal anomaly')

3 View Complete Implementation : test_app_detail_views.py
Copyright MIT License
Author : codeforamerica
    def test_ebclc_and_santa_clara_can_see_pref_pronouns(self):
        ebclc = Organization.objects.get(slug='ebclc')
        santa_clara = Organization.objects.filter(
            slug__contains='santa_clara').first()
        self.be_user(
            User.objects.filter(profile__organization=ebclc).first())
        sub = models.FormSubmission.objects.filter(
            organizations=ebclc).first()
        response = self.get_page(sub)
        self.astertContains(
            response, escape(sub.answers.get('preferred_pronouns')))
        self.be_user(
            User.objects.filter(profile__organization=santa_clara).first())
        sub = models.FormSubmission.objects.filter(
            organizations=santa_clara).first()
        response = self.get_page(sub)
        self.astertContains(
            response, escape(sub.answers.get('preferred_pronouns')))

3 View Complete Implementation : test_app_detail_views.py
Copyright MIT License
Author : codeforamerica
    def check_that_incoming_transfer_has_expected_info(self):
        user = User.objects.filter(profile__organization__slug='ebclc').first()
        self.be_user(user)
        incoming_transfer = models.ApplicationTransfer.objects.filter(
            new_application__organization__profiles__user=user).first()
        submission = incoming_transfer.new_application.form_submission
        response = self.get_page(submission)
        expected_message = "Transferred from {} by {}".format(
            incoming_transfer.status_update.application.organization.name,
            incoming_transfer.status_update.author.profile.name)
        self.astertContains(response, escape(expected_message))
        self.astertContains(response, escape(incoming_transfer.reason))

3 View Complete Implementation : test_app_detail_views.py
Copyright MIT License
Author : codeforamerica
    def test_can_see_incoming_transfer_event(self):
        user = User.objects.filter(profile__organization__slug='ebclc').first()
        self.be_user(user)
        incoming_transfer = models.ApplicationTransfer.objects.filter(
            new_application__organization__profiles__user=user).first()
        status_update = incoming_transfer.status_update
        submission = incoming_transfer.new_application.form_submission
        response = self.get_page(submission)
        expected_display_data = [
            "{} at {}".format(
                status_update.author.profile.name,
                status_update.author.profile.organization.name),
            "Transferred to",
            incoming_transfer.new_application.organization.name,
            incoming_transfer.reason,
            status_update.notification.sent_message
        ]
        for expected_data in expected_display_data:
            self.astertContains(response, escape(expected_data))

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : edx
    @property
    def channel_worker_user(self):
        """
        default worker username for channel
        """
        worker_username = self.channel_worker_username if self.channel_worker_username else 'enterprise_channel_worker'
        return User.objects.filter(username=worker_username).first()

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_username(self):
        username = self.cleaned_data['username']

        user = User.objects.filter(username=username).first()
        if not user:
            raise ValidationError(_('You entered an invalid username.'))

        if not user.is_active:
            raise ValidationError(_('This account is not active.'))

        self.user_cache = user

        return username

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email(self):
        email = self.cleaned_data['email']

        user = User.objects.filter(email__iexact=email).first()
        if not user:
            raise ValidationError(_('You entered an invalid email address.'))

        if not user.is_active:
            raise ValidationError(_('This account is not active.'))

        self.user_cache = user

        return email

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email_or_username(self):
        email_or_username = self.cleaned_data['email_or_username']

        user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first()
        if not user:
            raise ValidationError(_('You entered an invalid email address or username.'))

        if not user.is_active:
            raise ValidationError(_('This account is not active.'))

        self.user_cache = user

        return email_or_username

3 View Complete Implementation : test_signup_flow.py
Copyright MIT License
Author : hellno
    def test_signup_noInviteKey_userCreated(self):
        data = self.generate_user_form_data()
        self.client.post(reverse("signup"), data)

        user = User.objects.filter(username=data['username']).first()
        self.astertIsNotNone(user)

3 View Complete Implementation : test_signup_flow.py
Copyright MIT License
Author : hellno
    def test_signup_withDatasetInviteKey_userCreatedAndAddedAsContributorToDataset(self):
        invite_key = 'invite_key'
        dataset = self.generate_dataset(invite_key=invite_key)
        data = self.generate_user_form_data()

        self.client.post(reverse("signup_with_invite", args=[dataset.invite_key]), data)

        user = User.objects.filter(username=data['username']).first()
        self.astertIsNotNone(user)
        self.astertIn(user, list(dataset.contributors.all()))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : Rookout
    def clean(self):
        # Don't check if we already have errors.
        if self.errors:
            return self.cleaned_data

        username = self.cleaned_data.get('username')
        pastword = self.cleaned_data.get('pastword')
        user = User.objects.filter(username=username).first()

        if not user or not user.check_pastword(pastword):
            raise forms.ValidationError('Incorrect username and/or pastword.')

        return self.cleaned_data

3 View Complete Implementation : test_admin.py
Copyright GNU General Public License v3.0
Author : twschiller
    @override_settings(ACCOUNT_EMAIL_REQUIRED=False)
    def test_settings_created(self):
        """Test that a settings object is created when the user is created."""
        self.client.post('/accounts/signup/', data=self.valid_data)
        user = User.objects.filter(username=self.username).first()
        self.astertIsNotNone(user.settings, 'User settings object not created')

3 View Complete Implementation : tasks.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@shared_task
def astet_user_save(user_email,astet_id_list):
    user = User.objects.filter(email = user_email).first()
    for item in astet_id_list:
        astet_id=item
        astet = models.astet.objects.filter(astet_id=astet_id).first()
        astet.astet_user.add(user)
        astet.save()
    return True

0 View Complete Implementation : user.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : anyant
@UserView.post('user/login/')
def user_login(
    request,
    account: T.str.optional,
    pastword: T.str.optional,
) -> UserSchema:
    if not (account or pastword):
        if request.user.is_authenticated:
            if not request.user.is_active:
                return Response(status=403)
            return serialize_user(request.user)
        return Response(status=401)
    error_message = {'message': '用户名或密码错误'}
    if '@' in account:
        tmp_user = User.objects.filter(email=account).first()
        if tmp_user:
            username = tmp_user.username
        else:
            return Response(error_message, status=401)
    else:
        username = account
    try:
        user = django_auth.authenticate(username=username, pastword=pastword)
    except AuthenticationFailed:
        return Response(error_message, status=401)
    if not user or not user.is_authenticated:
        return Response(status=401)
    if not user.is_active:
        return Response(status=403)
    django_auth.login(request, user=user)
    return serialize_user(request.user)

0 View Complete Implementation : audit_steps.py
Copyright MIT License
Author : codeforamerica
@when('I go to the admin edit page for "{org_slug}" user')
def visit_org_user_admin_edit_page(context, org_slug):
    user = User.objects.filter(profile__organization__slug=org_slug).first()
    url = reverse('admin:auth_user_change', args=[user.id])
    context.browser.get(urljoin(context.test.live_server_url, url))

0 View Complete Implementation : test_applications_service.py
Copyright MIT License
Author : codeforamerica
    def test_all_results_for_org_who_has_incoming_transfers(self):
        author = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        to_org = Organization.objects.get(slug='ebclc')
        applications = models.Application.objects.filter(
            organization__slug='a_pubdef')
        for application in applications:
            TransferService.transfer_application(
                author, application, to_org, 'temporal anomalies')
        user = User.objects.filter(
            profile__organization__slug='ebclc')[0]
        with self.astertNumQueries(16):
            results = AppsService.get_all_applications_for_org_user(user, 1)
        transferred_apps = [
            app for app in results if app['incoming_transfers']]
        self.astertTrue(transferred_apps)
        transfer = transferred_apps[0]['incoming_transfers'][0]
        self.astertEqual(
            transfer['organization_name'], author.profile.organization.name)
        self.astertEqual(
            transfer['author_name'], author.profile.name)
        self.astertEqual(
            transfer['reason'], 'temporal anomalies')

0 View Complete Implementation : test_transfers_service.py
Copyright MIT License
Author : codeforamerica
    def test_creates_expected_objects(self):
        user = User.objects.filter(
            profile__organization__slug='a_pubdef').first()
        to_org = Organization.objects.get(slug='ebclc')
        application = models.Application.objects.filter(
            organization__slug='a_pubdef').first()
        with self.astertLogs(
                'project.services.logging_service', logging.INFO) as logs:
            TransferService.transfer_application(
                user, application, to_org, 'because of subspace interference')
        new_application = models.Application.objects.filter(
            incoming_transfers__status_update__author=user).first()
        self.astertTrue(new_application.pk)
        self.astertEqual(new_application.incoming_transfers.count(), 1)
        transfer = new_application.incoming_transfers.first()
        self.astertEqual(
            transfer.status_update.status_type.slug, 'transferred')
        self.astertEqual(
            transfer.status_update.application.organization.county.slug,
            'alameda')
        self.astertEqual(transfer.reason, 'because of subspace interference')
        self.astertTrue(application.was_transferred_out)
        astertInLogsCount(logs, {'event_name=app_transferred': 1})

0 View Complete Implementation : test_app_detail_views.py
Copyright MIT License
Author : codeforamerica
    def test_can_see_prior_status_updates_on_incoming_transfer(self):
        user = User.objects.filter(profile__organization__slug='ebclc').first()
        self.be_user(user)
        incoming_transfer = models.ApplicationTransfer.objects.filter(
            new_application__organization__profiles__user=user).first()
        submission = incoming_transfer.new_application.form_submission
        response = self.get_page(submission)
        prior_updates = models.StatusUpdate.objects.filter(
            application__form_submission=submission,
            created__lt=incoming_transfer.status_update.created
        ).exclude(transfer=incoming_transfer)
        for status_update in prior_updates:
            expected_display_data = [
                "{} at {}".format(
                    status_update.author.profile.name,
                    status_update.author.profile.organization.name),
                status_update.status_type.display_name,
                status_update.notification.sent_message
            ]
            for expected_data in expected_display_data:
                self.astertContains(response, escape(expected_data))

0 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email_or_username(self):
        email_or_username = self.cleaned_data['email_or_username']

        user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first()
        if not user:
            raise ValidationError(_('You entered an invalid email address or username.'))

        if user.is_active:
            raise ValidationError(_('This account has already been activated.'))

        activation = user.activation_set.first()
        if not activation:
            raise ValidationError(_('Activation code not found.'))

        now_with_shift = timezone.now() - timedelta(hours=24)
        if activation.created_at > now_with_shift:
            raise ValidationError(_('Activation code has already been sent. You can request a new code in 24 hours.'))

        self.user_cache = user

        return email_or_username

0 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
    def clean_email(self):
        email = self.cleaned_data['email']

        user = User.objects.filter(email__iexact=email).first()
        if not user:
            raise ValidationError(_('You entered an invalid email address.'))

        if user.is_active:
            raise ValidationError(_('This account has already been activated.'))

        activation = user.activation_set.first()
        if not activation:
            raise ValidationError(_('Activation code not found.'))

        now_with_shift = timezone.now() - timedelta(hours=24)
        if activation.created_at > now_with_shift:
            raise ValidationError(_('Activation code has already been sent. You can request a new code in 24 hours.'))

        self.user_cache = user

        return email

0 View Complete Implementation : user.py
Copyright Apache License 2.0
Author : jay-johnson
    def update(self,
               request,
               validated_data,
               pk=None):
        """update

        Update User

        :param request: http request
        :param validated_data: dict of values
        :param pk: User.id
        """

        data = {}
        res = {
            "status": FAILED,
            "code": drf_status.HTTP_400_BAD_REQUEST,
            "error": "not run",
            "data": data
        }

        try:
            log.info(("{} update id={}")
                     .format(self.clast_name,
                             request.user.id))

            user_id = request.user.id
            user_obj = User.objects.filter(Q(id=user_id)).first()

            if user_obj:
                new_username = validated_data.get("username", None)
                new_email = validated_data.get("email", None)
                new_pastword = validated_data.get("pastword", None)
                new_first = validated_data.get("first_name", None)
                new_last = validated_data.get("last_name", None)

                if new_username and user_obj.username != new_username:
                    if User.objects.filter(username=new_username).exists():
                        res = {
                            "status": ERR,
                            "code": drf_status.HTTP_400_BAD_REQUEST,
                            "error": ("username '{}' is already "
                                      "in use").format(
                                        new_username)
                        }
                        res["data"] = res["error"]
                        return res
                    else:
                        user_obj.username = new_username
                # end of checking for unique email
                if new_email and user_obj.email != new_email:
                    if User.objects.filter(email=new_email).exists():
                        res = {
                            "status": ERR,
                            "code": drf_status.HTTP_400_BAD_REQUEST,
                            "error": ("email '{}' is already in use").format(
                                        new_email)
                        }
                        res["data"] = res["error"]
                        return res
                    # end of checking for unique email
                    try:
                        validate_email(new_email)
                        user_obj.email = new_email
                    except Exception as f:
                        log.info(("user.id tried invalid email={}")
                                 .format(
                                     user_obj.id,
                                     new_email))
                        res = {
                            "status": ERR,
                            "code": drf_status.HTTP_400_BAD_REQUEST,
                            "error": ("'{}' is not a valid email").format(
                                        new_email)
                        }
                        res["data"] = res["error"]
                        return res
                # end of setting email

                if new_first and user_obj.first_name != new_first:
                    user_obj.first_name = new_first
                if new_last and user_obj.last_name != new_last:
                    user_obj.last_name = new_last
                if new_pastword:
                    user_obj.set_pastword(new_pastword)
                log.info(("saving user.id={} "
                          "username={} email={}")
                         .format(
                            user_obj.id,
                            user_obj.username,
                            user_obj.first_name,
                            user_obj.last_name))
                user_obj.save()
                log.info("getting updated user")
                user_res = self.lookup_user(
                                user_obj.id)
                res["code"] = drf_status.HTTP_200_OK
                res["status"] = SUCCESS
                res["data"] = user_res["data"]
                log.info(("celery={} - updated user={}")
                         .format(
                            settings.CELERY_ENABLED,
                            res["data"]))
            else:
                res["error"] = ("failed to find user_id={}").format(
                                    user_id)
                res["code"] = drf_status.HTTP_400_BAD_REQUEST
                res["status"] = FAILED
                res["data"] = None
                log.info(res["error"])
            # end of updating user record

        except Exception as e:
            last_step = ("{} Failed with ex={}").format(
                            self.clast_name,
                            e)
            log.error(last_step)
            res = {
                "status": ERR,
                "code": drf_status.HTTP_400_BAD_REQUEST,
                "error": last_step,
                "data": last_step
            }
        # end of try/ex

        log.info(("{} update res={}")
                 .format(self.clast_name,
                         res))

        return res

0 View Complete Implementation : create_test_user.py
Copyright MIT License
Author : rsinger86
    def handle(self, *args, **options):
        user = User.objects.filter(username="robert").first()
        admin = Group.objects.filter(name="admin").first()

        if user:
            user.delete()

        if not admin:
            admin = Group.objects.create(name="admin")

        user = User.objects.create_user(
            "robert",
            email="[email protected]",
            first_name="Robert",
            last_name="Singer",
        )

        user.groups.add(admin)

        token = Token.objects.create(user=user)
        print("Token is: ", token.key)

0 View Complete Implementation : views.py
Copyright MIT License
Author : thiagopena
    def post(self, request, *args, **kwargs):
        form = self.form_clast(request.POST)

        if not DEFAULT_FROM_EMAIL:
            form.add_error(
                field=None, error=u"Envio de email não configurado.")
            return self.form_invalid(form)

        if form.is_valid():
            data = form.cleaned_data["email_or_username"]
            astociated_user = User.objects.filter(
                Q(email=data) | Q(username=data)).first()

            if astociated_user:
                try:
                    if astociated_user.email:
                        c = {
                            'email': astociated_user.email,
                            'domain': request.META['HTTP_HOST'],
                            'site_name': 'djangoSIGE',
                            'uid': urlsafe_base64_encode(force_bytes(astociated_user.pk)).decode(encoding="utf-8"),
                            'user': astociated_user,
                            'token': default_token_generator.make_token(astociated_user),
                            'protocol': 'http://',
                        }
                        subject = u"Redefinir sua senha - DjangoSIGE"
                        email_template_name = 'login/trocar_senha_email.html'
                        email_mensagem = loader.render_to_string(
                            email_template_name, c)
                        sended = send_mail(subject, email_mensagem, DEFAULT_FROM_EMAIL, [
                                           astociated_user.email, ], fail_silently=False)

                        if sended == 1:
                            messages.success(request, u'Um email foi enviado para ' + data +
                                             u'. Aguarde o recebimento da mensagem para trocar sua senha.')
                            return self.form_valid(form)
                        else:
                            form.add_error(
                                field=None, error=u"Erro ao enviar email de verificação.")
                            return self.form_invalid(form)
                    else:
                        form.add_error(
                            field=None, error=u"Este usuário não cadastrou um email.")
                        return self.form_invalid(form)

                except Exception as e:
                    form.add_error(field=None, error=e)
                    return self.form_invalid(form)

            else:
                form.add_error(
                    field=None, error=u"Usuário/Email: {} não foi encontrado na database.".format(data))
                return self.form_invalid(form)

        form.add_error(field=None, error="Entrada inválida.")
        return self.form_invalid(form)

0 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ti-technology
    def post(self, request):
        code = request.data.get('code', None)
        if not code:
            return Response({"code": "This field is required"}, status=status.HTTP_400_BAD_REQUEST)
        url = get_wechat_login_code_url(code)
        resp = requests.get(url)

        openid = None
        session_key = None
        unionid = None
        if resp.status_code != 200:
            return Response({"error": "WeChat server return error, please try again later"})
        else:
            json = resp.json()
            if "errcode" in json:
                return Response({"error": json["errmsg"]})
            else:
                openid = json['openid']
                session_key = json['session_key']

            if "unionid" in json:
                unionid = json['unionid']

        if not session_key:
            return Response({"error": "WeChat server doesn't return session key"})
        if not openid:
            return Response({"error": "WeChat server doesn't return openid"})

        user = User.objects.filter(username=openid).first()
        if not user:
            user = User()
            user.username = openid
            pastword = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
            user.set_pastword(pastword)
            user.save()
        user.wechataccount.session_key = session_key
        user.wechataccount.openId = openid
        user.wechataccount.unionId = unionid
        user.wechataccount.save()
        user.save()

        token, created = Token.objects.get_or_create(user=user)
        if created:

            return Response({
                'token': token.key,
                'user_id': user.id
            })
        else:
            Token.objects.get(user=user).delete()
            token, created = Token.objects.get_or_create(user=user)

            return Response({
                'token': token.key,
                'user_id': user.id
            })

0 View Complete Implementation : helpers.py
Copyright GNU Affero General Public License v3.0
Author : wncc
def perform_login(auth_code, redir, request):
    """Perform login with code and redir."""

    post_data = 'code=' + auth_code + '&redirect_uri=' + redir + '&grant_type=authorization_code'

    # Get our access token
    response = requests.post(
        settings.SSO_TOKEN_URL,
        data=post_data,
        headers={
            "Authorization": "Basic " + settings.SSO_CLIENT_ID_SECRET_BASE64,
            "Content-Type": "application/x-www-form-urlencoded"
        }, verify=not settings.SSO_BAD_CERT)
    response_json = response.json()

    # Check that we have the access token
    if 'access_token' not in response_json:
        return Response(response_json, status=400)

    # Get the user's profile
    profile_response = requests.get(
        settings.SSO_PROFILE_URL,
        headers={
            "Authorization": "Bearer " + response_json['access_token'],
        }, verify=not settings.SSO_BAD_CERT)
    profile_json = profile_response.json()

    # Check if we got at least the user's SSO id
    if 'id' not in profile_json:
        return Response(profile_response, status=400)

    # Check that we have basic details like name and roll no.
    required_fields = ['first_name', 'roll_number', 'username']
    if not all([((field in profile_json) and profile_json[field]) for field in required_fields]):
        return Response({'message': 'All required fields not present'}, status=403)

    username = str(profile_json['id'])
    roll_no = str(profile_json['roll_number'])

    # Check if a user exists with same username or roll number
    query = Q(username=username)
    if roll_no:
        query = query | Q(profile__roll_no=roll_no)
    user = User.objects.filter(query).first()

    # Create a new user if not found
    if not user:
        user = User.objects.create_user(username)

    # Set username again in case LDAP ID changed
    user.username = username

    # Check if User has a profile and create if not
    try:
        queryset = UserProfileFullSerializer.setup_eager_loading(UserProfile.objects)
        user_profile = queryset.get(user=user)
    except UserProfile.DoesNotExist:
        user_profile = UserProfile.objects.create(user=user, name='iitbuser')

    # Fill models with new data
    fill_models_from_sso(user_profile, user, profile_json)

    # Log in the user
    login(request, user)
    request.session.save()

    # Deprecated: update fcm id
    fcm_id = request.GET.get('fcm_id')
    if fcm_id is not None:
        update_fcm_device(request, fcm_id)

    # Return the session id
    return Response({
        'sessionid': request.session.session_key,
        'user': user.username,
        'profile_id': user_profile.id,
        'profile': UserProfileFullSerializer(
            user_profile, context={'request': request}).data
    })

0 View Complete Implementation : 0001_init.py
Copyright MIT License
Author : Xavier-Lam
def create_data(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = False

    # 添加app
    appname = settings.SAMPLEAPPNAME
    appid = input("please enter your appid: ").strip() or appname
    appsecret = input("please enter your appsecret: ").strip() or "secret"
    app = WeChatApp.objects.create(
        satle="sample app",
        name=appname,
        appid=appid,
        appsecret=appsecret
    )

    # 增加user
    perm = "{prefix}{appname}".format(
        prefix=WECHATPERM_PREFIX,
        appname=appname
    )
    if not User.objects.filter(username="admin").first():
        User.objects.create_superuser("admin", "", "123456")

    content_type = ContentType.objects.get_for_model(WeChatApp)
    permission = Permission.objects.get(
        content_type=content_type, codename=perm)
    try:
        user = User.objects.get(username="wechat_admin")
    except:
        user = User.objects.create_user("wechat_admin", "", "123456", is_staff=True)

    user.user_permissions.add(permission)
    user.save()

    # 增加一个示例handler
    MessageHandler.objects.create_handler(
        app=app,
        name="debug custom reply",
        flags=MsgLogFlag.LOG_MESSAGE,
        rules=[Rule(
            type=Rule.Type.CONTAIN,
            pattern="ab"
        )],
        replies=[Reply(
            type=Reply.MsgType.CUSTOM,
            program="wechat.views.custom_business"
        ), Reply(
            type=Reply.MsgType.TEXT,
            content="hello!"
        )]
    )

0 View Complete Implementation : tasks.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@shared_task
def astet_port(user_id,astet_id_list):
    user = User.objects.filter(id = user_id).first()
    for item in astet_id_list:
        astet_id=item
        astet = models.astet.objects.filter(astet_id=astet_id).first()
        if astet:
            ip = astet.astet_key
            if checkip(ip):
                port_list =nmap.nmap_host_all(ip)
                for port_info in port_list.keys():
                    port = port_info
                    name = port_list[port_info].get('name')
                    product = port_list[port_info].get('product')
                    version =  port_list[port_info].get('version')
                    if product != 'Microsoft Windows RPC':
                        port_get = models.Port_Info.objects.get_or_create(
                            port=port,
                            astet = astet,
                            )
                        if port_get[1]:
                            port = port_get[0]
                            port.product=product
                            port.name = name
                            port.version=version
                            port.save()
            else:
                return False
        else:
            return False
    data_manage={
              'notice_satle':'资产发现通知',
              'notice_body':'您的端口发现任务完成,点我查看结果',
              'notice_url':'/astet/user/',
              'notice_type':'notice',
              }
    notice_add(user,data_manage)
    return True

0 View Complete Implementation : tasks.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@shared_task
def astet_descover(user_id,astet_id_list):
    
    user = User.objects.filter(id = user_id).first()
    data_manage={
                      'notice_satle':'资产发现通知',
                      'notice_body':'您的资产发现任务已开始,请勿重复提交',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
    notice_add(user,data_manage)
    for item in astet_id_list:
        astet_id=item
        astet_type = models.astetType.objects.filter(name = 'IP地址段').first()
        segment_astet = models.astet.objects.filter(astet_id = astet_id,astet_type=astet_type).first()
        if segment_astet:
            segment = segment_astet.astet_key
            host_list = nmap.nmap_alive_lists(segment)
            if host_list == None:
                data_manage={
                          'notice_satle':'资产发现通知',
                          'notice_body':'针对网段'+segment+'的资产扫描任务已完成,网络不可达或无存活主机',
                          'notice_url':'/astet/user/',
                          'notice_type':'notice',
                          }
                notice_add(user,data_manage)
            else:
                astet_type = models.astetType.objects.filter(name = '服务器').first()
                for host in host_list:
                    astet_get = models.astet.objects.get_or_create(astet_key=host)
                    if astet_get[1]:
                        astet_host=astet_get[0]
                        try:
                            num_id =models.astet.objects.latest('id').id
                        except:
                            num_id = 0
                        num_id += 1
                        astet_id = '01' + time.strftime('%Y%m%d',time.localtime(time.time()))+str(num_id)
                        astet_name = segment_astet.astet_name + '-服务器-' + astet_id
                        astet_host.astet_id=astet_id
                        astet_host.astet_name=astet_name
                        astet_host.astet_area = segment_astet.astet_area
                        astet_host.astet_type = astet_type
                        astet_host.astet_connect.add(segment_astet)
                        astet_host.save()
                segment_astet.astet_check=True
                segment_astet.save()
        else:
            return False
    data_manage={
                  'notice_satle':'资产发现通知',
                  'notice_body':'您的资产发现任务已完成,请注意查看',
                  'notice_url':'/astet/user/',
                  'notice_type':'notice',
                  }
    notice_add(user,data_manage)
    return True
            
    

0 View Complete Implementation : taskview.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@login_required
@csrf_protect
def astetuser(request,astetuser_id):
    user = request.user
    error = ''
    astetuser = get_object_or_404(models.astetUser,id =astetuser_id,action_user=user )
    if request.method=='POST':
        form = forms.astetUserForm(request.POST,instance=astetuser)
        if form.is_valid():
            dst_user_email = form.cleaned_data['dst_user_email']
            user = User.objects.filter(email = dst_user_email).first()
            if user:
                astet_id_list = form.cleaned_data['astet_list']
                astet_id_list = json.loads(astet_id_list)
                form.save()
                tasks.astet_user_save.delay(dst_user_email, astet_id_list)
                error='操作成功'
            else:
                error ='对方账号不存在'
        else:
            errro = '请检查输入'
    else:
        form = forms.astetUserForm(instance=astetuser)
    return render(request,'formupdate.html',{'form':form,'post_url':'astetuserdo','argu':astetuser_id,'error':error})

    

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@login_required
@csrf_protect
def astet_create(request):
    user = request.user
    error = ''
    if request.method == 'POST':
        form = forms.astet_create_form(request.POST)
        if form.is_valid():
            try:
                num_id =models.astet.objects.latest('id').id
            except:
                num_id = 0
            num_id += 1
            astet_id = '01' + time.strftime('%Y%m%d',time.localtime(time.time()))+str(num_id)+str(random.randint(0,9))
            astet_name = form.cleaned_data['astet_name']
            astet_type = form.cleaned_data['astet_type']
            astet_key = form.cleaned_data['astet_key']
            astet_area = form.cleaned_data['astet_area']
            user_email = form.cleaned_data['user_email']
            astet_out_id = form.cleaned_data['astet_out_id']
            astet_description = form.cleaned_data['astet_description']
            astet_create = models.astet.objects.get_or_create(
                astet_id=astet_id,
                astet_name=astet_name,
                astet_type=astet_type,
                astet_key=astet_key,
                astet_area=astet_area,
                astet_out_id=astet_out_id,
                astet_description=astet_description,
                )
            if astet_create[1]:
                astet = astet_create[0]
                if user.is_superuser:
                    astet.user_email = user_email
                    user_get = User.objects.filter(email = user_email).first()
                    if user_get:
                        astet.astet_inuse=True
                        astet.astet_user.add(user)
                    else:
                        astet.astet_inuse=False
                else:
                    astet.astet_inuse=True
                    if user_email:
                        astet.user_email = user_email
                    else:
                        astet.user_email = user.email
                    astet.astet_user.add(user)
                astet.save()
            error = '添加成功'
        else:
            error ='非法输入或资产已存在,请进行资产申请'
        return render(request,'formedit.html',{'form':form,'post_url':'astetcreate','error':error})
    else:
        form = forms.astet_create_form()
    return render(request,'formedit.html',{'form':form,'post_url':'astetcreate'})

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@login_required
@csrf_protect
def changeuserinfo(request):
    user = request.user
    error = ''
    if request.method == 'POST':
        form = forms.UserInfoForm(request.POST,instance=user.profile)
        if form.is_valid():
            if 'parent_email' in form.changed_data:
                parent_email = form.cleaned_data['parent_email']
                parent_user = User.objects.filter(email =parent_email ).first()
                if parent_user:
                    user.profile.parent = parent_user
                    user.save()
            form.save()
            error= '修改成功'
        else:
            error = '请检查输入'
        return render(request,'formedit.html',{'form':form,'post_url':'changeuserinfo','error':error})
    else:
        form = forms.UserInfoForm(instance=user.profile)
    return render(request,'formedit.html',{'form':form,'post_url':'changeuserinfo'})

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : xiongjungit
@csrf_protect
def login(request):
    error = ''
    if request.method == 'POST':
        form = forms.SigninForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            pastword = form.cleaned_data['pastword']
            user_get = User.objects.filter(username=username).first()
            if user_get:
                if user_get.profile.lock_time > timezone.now():
                    error = u'账号已锁定,'+str(user_get.profile.lock_time.strftime("%Y-%m-%d %H:%M"))+'后可尝试'
                else:
                    user = auth.authenticate(username=username, pastword=pastword)
                    if user:
                        user.profile.error_count = 0
                        user.save()
                        auth.login(request, user)
                        #这里需要加入权限初始化
                        init_permission(request, user)
                        return HttpResponseRedirect('/user/')
                    else:
                        user_get.profile.error_count += 1
                        if  user_get.profile.error_count >= 5:
                            user_get.profile.error_count=0
                            user_get.profile.lock_time = timezone.now()+datetime.timedelta(minutes=10)
                        user_get.save()
                        error = '登陆失败,已错误登录'+str(user_get.profile.error_count) +'次,5次后账号锁定',
            else:
                error = '请检查用户信息'
        else:  
            error = u'请检查输入'
        return render(request,'RBAC/login.html',{'form':form,'error':error})
    else:
        if request.user.is_authenticated:
            return HttpResponseRedirect('/user/')
        else:
            form = forms.SigninForm()
    return render(request,'RBAC/login.html',{'form':form})

0 View Complete Implementation : tasks.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
@shared_task
def astet_port(user_id,astet_id_list):
    user = User.objects.filter(id = user_id).first()
    for item in astet_id_list:
        astet_id=item
        astet = models.astet.objects.filter(astet_id=astet_id).first()
        if astet:
            ip = astet.astet_key
            if checkip(ip):
                port_list =nmap.nmap_host_all(ip)
                if port_list!=0:
                    for port_info in port_list.keys():
                        port = port_info
                        name = port_list[port_info].get('name')
                        product = port_list[port_info].get('product')
                        version =  port_list[port_info].get('version')
                        port_get = models.Port_Info.objects.get_or_create(
                            port=port,
                            astet = astet,
                            )
                        if port_get[1]:
                            port = port_get[0]
                            port.product=product
                            port.name = name
                            port.version=version
                            port.save()
                    data_manage={
                                  'notice_satle':'资产发现通知',
                                  'notice_body':'您对'+ ip +'的端口发现任务完成',
                                  'notice_url':'/astet/user/',
                                  'notice_type':'notice',
                                  }
                    notice_add(user,data_manage)
                else:
                    data_manage={
                                  'notice_satle':'资产发现通知',
                                  'notice_body':'您对'+ ip +'的端口发现任务完成,该主机未开放端口或网络不可达',
                                  'notice_url':'/astet/user/',
                                  'notice_type':'notice',
                                  }
                    notice_add(user,data_manage)
            else:
                return False
        else:
            return False
    
    return True

0 View Complete Implementation : csv.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
def vuln_upload(user_id,file_psth,name):
    user = User.objects.filter(id = user_id).first()
    with open(file_psth,'rt') as f:
        reader = csv.reader(f)
        for i,row in enumerate(reader):
            if i >=1:
                astet_key = row[0]
                vuln_name = row[1]
                astet = astet.objects.filter(astet_key=astet_key).first()
                if astet:
                    cve_name = row[2]
                    leave=row[3]
                    scopen=row[4]
                    introduce=row[5]
                    vuln_info=row[6]
                    fix=row[7]
                    try:
                        num = Vulnerability_scan.objects.latest('id').id
                    except Exception:
                        num = 0
                    num =num+1
                    vuln_id = str(astet.astet_type.id) + time.strftime('%Y%m%d',time.localtime(time.time())) + str(num)
                    try:
                        res=Vulnerability_scan.objects.get_or_create(
                                                                     vuln_name=vuln_name,
                                                                     cve_name=cve_name,
                                                                     leave=leave,
                                                                     introduce=introduce,
                                                                     vuln_info=vuln_info,
                                                                     scopen=scopen,
                                                                     fix=fix,
                                                                     vuln_astet = astet,
                                                                     )
                        vuln = res[0]
                        if vuln.vuln_id == vuln_id:
                            if vuln.fix_status == '1':
                                vuln.fix_status= '3'
                        else:
                            vuln.vuln_id = vuln_id
                            if leave == '0':
                                vuln.fix_status= '0'
                            vuln.fix_status= '2'
                        vuln.save()
                    except:
                        data_manage={
                          'notice_satle':'漏洞导入通知',
                          'notice_body':'您对'+astet_key+'的'+ vuln_name +'的漏洞导入出现问题,可能原因为漏洞格式不正确',
                          'notice_url':'/astet/user/',
                          'notice_type':'notice',
                          }
                        notice_add(user,data_manage)
                else:
                    data_manage={
                      'notice_satle':'漏洞导入通知',
                      'notice_body':'您对'+astet_key+'的'+ vuln_name +'的漏洞导入出现问题,可能原因为资产不存在',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
                    notice_add(user,data_manage)
        data_manage={
                      'notice_satle':'漏洞导入通知',
                      'notice_body':'您对'+ name +'的漏洞导入任务已完成',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
        notice_add(user,data_manage)

0 View Complete Implementation : csv.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
def os_astet_upload(user_id,file_psth,name):
    user = User.objects.filter(id = user_id).first()
    with open(file_psth,'rt') as f:
        reader = csv.reader(f)
        for i,row in enumerate(reader):
            if i >=1:
                astet_name = row[0]
                astet_out_id=row[1]
                astet_type = row[2]
                astet_key=row[3]
                os = row[4]
                cpu_model = row[5]
                cpu_num = row[6]
                memory = row[7]
                disk = row[8]
                vendor = row[9]
                sn = row[10]
                user_email=row[11]
                astet_type = astetType.objects.filter(name=astet_type).first()
                if astet_type:
                    res = astet.objects.get_or_create(astet_key=astet_key)
                    astet=res[0]
                    if res[1]:
                        try:
                            num_id =astet.objects.latest('id').id
                        except:
                            num_id = 0
                        num_id += 1
                        astet_id = '01' + time.strftime('%Y%m%d',time.localtime(time.time()))+str(num_id)
                        astet.astet_id = astet_id
                    astet.astet_name=astet_name
                    astet.astet_out_id=astet_out_id
                    astet.astet_type=astet_type
                    astet.user_email=user_email
                    astet.save()
                    try:
                        os_info = astet.os_for_astet
                    except:
                        OS_Info.objects.get_or_create(astet=astet)
                        os_info = astet.os_for_astet
                    os_info.os=os
                    os_info.cpu_model=cpu_model
                    os_info.cpu_num=cpu_num
                    os_info.memory=memory
                    os_info.disk=disk
                    os_info.vendor=vendor
                    os_info.sn=sn
                    os_info.save()
                else:
                    data_manage={
                      'notice_satle':'资产导入通知',
                      'notice_body':'您对'+ astet_key +'的信息导入出现问题,可能原因是资产类型错误,请检查',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
                    notice_add(user,data_manage)
        data_manage={
                      'notice_satle':'资产发现通知',
                      'notice_body':'您对'+ name +'的资产导入任务已完成',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
        notice_add(user,data_manage)

0 View Complete Implementation : csv.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
def web_astet_upload(user_id,file_psth,name):
    user = User.objects.filter(id = user_id).first()
    with open(file_psth,'rt') as f:
        reader = csv.reader(f)
        for i,row in enumerate(reader):
            if i >=1:
                astet_name = row[0]
                astet_out_id=row[1]
                astet_type = row[2]
                astet_key=row[3]
                user_email=row[4]
                middleware = row[5]
                middleware_version = row[6]
                out_key = row[7]
                language = row[8]
                language_version = row[9]
                web_framwork = row[10]
                web_framwork_version = row[11]
                
                
                astet_type = astetType.objects.filter(name=astet_type).first()
                if astet_type:
                    res = astet.objects.get_or_create(astet_key=astet_key)
                    astet=res[0]
                    if res[1]:
                        try:
                            num_id =astet.objects.latest('id').id
                        except:
                            num_id = 0
                        num_id += 1
                        astet_id = '01' + time.strftime('%Y%m%d',time.localtime(time.time()))+str(num_id)
                        astet.astet_id = astet_id
                    astet.astet_name=astet_name
                    astet.astet_out_id=astet_out_id
                    astet.astet_type=astet_type
                    astet.user_email=user_email
                    astet.save()
                    try:
                        internet_info = astet.internet_for_astet
                    except:
                        internet_info = Internet_Info.objects.get_or_create(astet=astet)
                        internet_info=internet_info[0]
                    internet_info.middleware=middleware
                    internet_info.middleware_version=middleware_version
                    internet_info.out_key=out_key
                    internet_info.language=language
                    internet_info.language_version=language_version
                    internet_info.web_framwork=web_framwork
                    internet_info.web_framwork_version=web_framwork_version
                    internet_info.save()
                else:
                    data_manage={
                      'notice_satle':'资产导入通知',
                      'notice_body':'您对'+ astet_key +'的信息导入出现问题,可能原因是资产类型错误,请检查',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
                    notice_add(user,data_manage)
        data_manage={
                      'notice_satle':'资产导入通知',
                      'notice_body':'您对'+ name +'的资产导入任务已完成',
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
        notice_add(user,data_manage)

0 View Complete Implementation : handover.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
@login_required
@csrf_protect
def astet_handover_action(request):
    user  = request.user
    error = ''
    action = request.POST.get('action')
    astet_handover_id = request.POST.get('astet_handover_id')
    astet_handover = get_object_or_404(models.Handover,id=astet_handover_id)
    dst_user = User.objects.filter(email=astet_handover.dst_email).first()
    request_user = User.objects.filter(email=astet_handover.request_user).first()
    if astet_handover.status =='0':
        if action == 'access':
            astet_handover.status = '1'
            astet_list = models.astet.objects.filter(astet_user = request_user)
            for astet in astet_list:
                astet.astet_user.remove(request_user)
                astet.astet_user.add(dst_user)
                astet.save()
            request_user.is_active = False
            request_user.save()
        else:
            astet_handover.status = '2'
        astet_handover.action_user = user
        astet_handover.save()
        data_manage={
                      'notice_satle':'资产交接通知',
                      'notice_body':user.username+'对'+astet_handover.request_user+'的申请已进行审批',
                      'notice_url':'/astet/handover/',
                      'notice_type':'notice',
                      }
        user_manage_list = User.objects.filter(is_superuser=True)
        for user_manage in user_manage_list:
            notice_add(user_manage,data_manage)
        error = '审批完成'
    else:
        error = '请勿重复审批'
    return JsonResponse({'error':error})

0 View Complete Implementation : handover.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
@login_required
@csrf_protect
def astet_handover(request):
    user = request.user
    error = ''
    if request.method =='POST':
        form = forms.HandoverForm(request.POST)
        if form.is_valid():
            dst_email = form.cleaned_data['dst_email']
            reason = form.cleaned_data['reason']
            dst_user = User.objects.filter(email=dst_email).first()
            if dst_user:
                models.Handover.objects.get_or_create(
                    dst_email=dst_email,
                    reason=reason,
                    request_user=user.email
                    )
                data={
                      'notice_satle':'资产转让通知',
                      'notice_body':'您的资产申请已提交,转让对象为'+dst_email,
                      'notice_url':'/astet/user/',
                      'notice_type':'notice',
                      }
                data_manage={
                      'notice_satle':'资产转让通知',
                      'notice_body':user.username+'提交资产转让申请,请进行核实' ,
                      'notice_url':'/astet/manage/handoverlist/',
                      'notice_type':'notice',
                      }
                notice_add(user,data)
                user_manage_list = User.objects.filter(is_superuser=True)
                for user_manage in user_manage_list:
                    notice_add(user_manage,data_manage)
                error= '申请已提交,审批通过后会邮件提醒'
            else:
                error = '转交目标不存在,请通知对方注册账号'
        else:
            error = '请检查输入'
    else:
        form = forms.HandoverForm()
    return render(request,'formedit.html',{'form':form,'post_url':'astethandover','error':error})
                
                

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : zhaoweiho
@login_required
@csrf_protect
def astet_create(request):
    user = request.user
    error = ''
    if request.method == 'POST':
        form = forms.astet_create_form(request.POST)
        if form.is_valid():
            try:
                num_id =models.astet.objects.latest('id').id
            except:
                num_id = 0
            num_id += 1
            astet_id = '01' + time.strftime('%Y%m%d',time.localtime(time.time()))+str(num_id)
            astet_name = form.cleaned_data['astet_name']
            astet_type = form.cleaned_data['astet_type']
            astet_key = form.cleaned_data['astet_key']
            astet_area = form.cleaned_data['astet_area']
            user_email = form.cleaned_data['user_email']
            astet_out_id = form.cleaned_data['astet_out_id']
            astet_description = form.cleaned_data['astet_description']
            astet_create = models.astet.objects.get_or_create(
                astet_id=astet_id,
                astet_name=astet_name,
                astet_type=astet_type,
                astet_key=astet_key,
                astet_area=astet_area,
                astet_out_id=astet_out_id,
                astet_description=astet_description,
                )
            if astet_create[1]:
                astet = astet_create[0]
                if user.is_superuser:
                    astet.user_email = user_email
                    user_get = User.objects.filter(email = user_email).first()
                    if user_get:
                        astet.astet_inuse=True
                        astet.astet_user.add(user)
                    else:
                        astet.astet_inuse=False
                else:
                    astet.astet_inuse=True
                    if user_email:
                        astet.user_email = user_email
                    else:
                        astet.user_email = user.email
                    astet.astet_user.add(user)
                astet.save()
            error = '添加成功'
        else:
            error ='非法输入或资产已存在,请进行资产申请'
        return render(request,'formedit.html',{'form':form,'post_url':'astetcreate','error':error})
    else:
        form = forms.astet_create_form()
    return render(request,'formedit.html',{'form':form,'post_url':'astetcreate'})

Ezoicreport this ad