当前位置: 首页>>代码示例>>Python>>正文


Python UserProfile.save方法代码示例

本文整理汇总了Python中student.models.UserProfile.save方法的典型用法代码示例。如果您正苦于以下问题:Python UserProfile.save方法的具体用法?Python UserProfile.save怎么用?Python UserProfile.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在student.models.UserProfile的用法示例。


在下文中一共展示了UserProfile.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: make_student

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
    def make_student(self, block, name, **state):
        answer = {}
        for key in ("sha1", "mimetype", "filename"):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop("score", None)

        user = User(username=name)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        module = StudentModule(
            module_state_key=block.location, student=user, course_id=self.course_id, state=json.dumps(state)
        )
        module.save()

        anonymous_id = anonymous_id_for_user(user, self.course_id)
        item = StudentItem(student_id=anonymous_id, course_id=self.course_id, item_id=block.block_id, item_type="sga")
        item.save()

        if answer:
            student_id = block.student_submission_id(anonymous_id)
            submission = submissions_api.create_submission(student_id, answer)
            if score is not None:
                submissions_api.set_score(submission["uuid"], score, block.max_score())
        else:
            submission = None

        self.addCleanup(item.delete)
        self.addCleanup(profile.delete)
        self.addCleanup(module.delete)
        self.addCleanup(user.delete)

        return {"module": module, "item": item, "submission": submission}
开发者ID:eduNEXT,项目名称:edunext-sga,代码行数:36,代码来源:tests.py

示例2: setUp

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
    def setUp(self):
        self.test_server_prefix = 'https://testserver'
        self.base_organizations_uri = '/api/server/organizations/'
        self.base_users_uri = '/api/server/users'
        self.base_groups_uri = '/api/server/groups'
        self.test_organization_name = str(uuid.uuid4())
        self.test_organization_display_name = 'Test Org'
        self.test_organization_contact_name = 'John Org'
        self.test_organization_contact_email = '[email protected]'
        self.test_organization_contact_phone = '+1 332 232 24234'

        self.test_user_email = str(uuid.uuid4())
        self.test_user_username = str(uuid.uuid4())
        self.test_user = User.objects.create(
            email=self.test_user_email,
            username=self.test_user_username
        )
        profile = UserProfile(user=self.test_user)
        profile.city = 'Boston'
        profile.save()

        self.course = CourseFactory.create()
        self.second_course = CourseFactory.create(
            number="899"
        )

        self.client = SecureClient()
        cache.clear()
开发者ID:eduStack,项目名称:edx-serverapi,代码行数:30,代码来源:tests.py

示例3: create_lti_user

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def create_lti_user(lti_user_id, lti_consumer):
    """
    Generate a new user on the edX platform with a random username and password,
    and associates that account with the LTI identity.
    """
    edx_password = str(uuid.uuid4())

    created = False
    while not created:
        try:
            edx_user_id = generate_random_edx_username()
            edx_email = "{}@{}".format(edx_user_id, settings.LTI_USER_EMAIL_DOMAIN)
            edx_user = User.objects.create_user(
                username=edx_user_id,
                password=edx_password,
                email=edx_email,
            )
            # A profile is required if PREVENT_CONCURRENT_LOGINS flag is set.
            # TODO: We could populate user information from the LTI launch here,
            # but it's not necessary for our current uses.
            edx_user_profile = UserProfile(user=edx_user)
            edx_user_profile.save()
            created = True
        except IntegrityError:
            # The random edx_user_id wasn't unique. Since 'created' is still
            # False, we will retry with a different random ID.
            pass

    lti_user = LtiUser(
        lti_consumer=lti_consumer,
        lti_user_id=lti_user_id,
        edx_user=edx_user
    )
    lti_user.save()
    return lti_user
开发者ID:189140879,项目名称:edx-platform,代码行数:37,代码来源:users.py

示例4: user_submit

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def user_submit(request):
    if not request.user.is_authenticated:
        raise Http404
    try:
        if request.POST.get('id'):
            profile=UserProfile.objects.get(user_id=request.POST['id'])
            user=User.objects.get(id=request.POST['id'])
        else:
            profile=UserProfile()
            user=User()

        if request.POST['subscription_status']=='Registered':
            user.is_active=True
        else:
            user.is_active=False

        user.email=request.POST['email']
        user.save()

        profile.user_id=user.id
        profile.school_id=request.POST['school_id']
        profile.cohort_id=request.POST['cohort_id']
        profile.district_id=request.POST['district_id']
        profile.subscription_status=request.POST['subscription_status']
        profile.save()

    except Exception as e:
        db.transaction.rollback()
        return HttpResponse(json.dumps({'success': False,'error':'%s' % e}))
    return HttpResponse(json.dumps({'success': True}))
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:32,代码来源:views.py

示例5: import_user

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def import_user(u):
    user_info = u["u"]
    up_info = u["up"]

    # HACK to handle dates
    user_info["last_login"] = dateutil.parser.parse(user_info["last_login"])
    user_info["date_joined"] = dateutil.parser.parse(user_info["date_joined"])

    user_keys = [
        "id",
        "username",
        "email",
        "password",
        "is_staff",
        "is_active",
        "is_superuser",
        "last_login",
        "date_joined",
        "password",
    ]
    up_keys = ["language", "location", "meta", "name", "id", "user_id"]

    u = User()
    for key in user_keys:
        u.__setattr__(key, user_info[key])
    u.save()

    up = UserProfile()
    up.user = u
    for key in up_keys:
        up.__setattr__(key, up_info[key])
    up.save()
开发者ID:juancamilom,项目名称:edx-platform,代码行数:34,代码来源:6002importusers.py

示例6: import_user_submit

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def import_user_submit(request):
    message={}
    if request.method == 'POST':
        f=request.FILES['file']
        try:
            count_success=0
            # --- THIS FAILS ON SING COLUMN CVS ---
            # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
            # f.seek(0)
            # r=csv.reader(f,dialect)
            r=csv.reader(f,delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            rl = []
            rl.extend(r)
            cohort_id=request.POST.get("cohort_id")
            cohort=Cohort.objects.get(id=cohort_id)
            if cohort.licences < UserProfile.objects.filter(~Q(subscription_status = "Inactive"),cohort_id=cohort_id).count() + len(rl):
                raise Exception("Licences limit exceeded")
            for line in rl:
                exist=validate_user_cvs_line(line)
                # if(exist):
                #     raise Exception("An user already exists, or duplicate lines.")
                email=line[USER_CSV_COL_EMAIL]
                import random
                username=random_mark(20)
                user = User(username=username, email=email, is_active=False)
                user.set_password(username)
                user.save()
                registration = Registration()
                registration.register(user)
                profile=UserProfile(user=user)
                # profile.transaction_id=transaction_id
                # profile.email=email
                # profile.username=username
                profile.cohort_id=cohort_id
                profile.subscription_status="Imported"
                profile.save()

                cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id='PCG_Education/PEP101.1/S2016', email=email)
                cea.is_active = True
                cea.auto_enroll = True
                cea.save()

                count_success=count_success+1

                # reg = Registration.objects.get(user=user)
                # d = {'name': profile.name, 'key': reg.activation_key}
                # subject = render_to_string('emails/activation_email_subject.txt', d)
                # subject = ''.join(subject.splitlines())
                # message = render_to_string('emails/activation_emailh.txt', d)
            db.transaction.commit()
            message={"success": True,
                "message":"Success! %s users imported." % (count_success),
                "count_success":count_success,
            }
        except Exception as e:
            db.transaction.rollback()
            message={'success': False,'error':'Import error: %s. At cvs line: %s, Nobody imported.' % (e,count_success+1)}
    return HttpResponse(json.dumps(message))
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:60,代码来源:views.py

示例7: import_user_submit

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def import_user_submit(request):
    message = {}
    if request.method == "POST":
        f = request.FILES["file"]
        try:
            count_success = 0
            count_exist = 0
            # --- THIS FAILS ON SING COLUMN CVS ---
            # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
            # f.seek(0)
            # r=csv.reader(f,dialect)
            r = csv.reader(f, delimiter="\t", quotechar="|", quoting=csv.QUOTE_MINIMAL)
            rl = []
            rl.extend(r)
            cohort_id = request.POST.get("cohort_id")
            cohort = Cohort.objects.get(id=cohort_id)
            if cohort.licences < UserProfile.objects.filter(cohort_id=cohort_id).count() + len(rl):
                raise Exception("Licences limit exceeded")
            for line in rl:
                exist = validate_user_cvs_line(line)
                # if(exist):
                #     raise Exception("An user already exists, or duplicate lines.")
                email = line[USER_CVS_COL_EMAIL]
                import random

                username = "".join(random.sample("abcdefg&#%^*f1234567890", 20))
                user = User(username=username, email=email, is_active=True)
                user.set_password(username)
                user.save()
                registration = Registration()
                registration.register(user)
                profile = UserProfile(user=user)
                # profile.transaction_id=transaction_id
                # profile.email=email
                # profile.username=username
                profile.cohort_id = cohort_id
                profile.subscription_status = "Imported"
                profile.save()
                # reg = Registration.objects.get(user=user)
                # d = {'name': profile.name, 'key': reg.activation_key}
                # subject = render_to_string('emails/activation_email_subject.txt', d)
                # subject = ''.join(subject.splitlines())
                # message = render_to_string('emails/activation_email.txt', d)
            db.transaction.commit()
            message = {
                "success": True,
                "message": "Success! %s users imported." % (count_success),
                "count_exist": count_exist,
                "count_success": count_success,
            }
        except Exception as e:
            db.transaction.rollback()
            message = {
                "success": False,
                "error": "Import error: %s. At cvs line: %s, Nobody imported." % (e, count_success + 1),
            }
    return HttpResponse(json.dumps(message))
开发者ID:EduPepperPD,项目名称:pepper2013,代码行数:59,代码来源:views.py

示例8: make_student

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
    def make_student(self, block, name, make_state=True, **state):
        """
        Create a student along with submission state.
        """
        answer = {}
        module = None
        for key in ('sha1', 'mimetype', 'filename', 'finalized'):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop('score', None)

        with transaction.atomic():
            user = User(username=name)
            user.save()
            profile = UserProfile(user=user, name=name)
            profile.save()
            if make_state:
                module = StudentModule(
                    module_state_key=block.location,
                    student=user,
                    course_id=self.course_id,
                    state=json.dumps(state))
                module.save()

            anonymous_id = anonymous_id_for_user(user, self.course_id)
            item = StudentItem(
                student_id=anonymous_id,
                course_id=self.course_id,
                item_id=block.block_id,
                item_type='sga')
            item.save()

            if answer:
                student_id = block.get_student_item_dict(anonymous_id)
                submission = submissions_api.create_submission(student_id, answer)
                if score is not None:
                    submissions_api.set_score(
                        submission['uuid'], score, block.max_score())
            else:
                submission = None

            self.addCleanup(item.delete)
            self.addCleanup(profile.delete)
            self.addCleanup(user.delete)

            if make_state:
                self.addCleanup(module.delete)
                return {
                    'module': module,
                    'item': item,
                    'submission': submission
                }

            return {
                'item': item,
                'submission': submission
            }
开发者ID:doctoryes,项目名称:edx-sga,代码行数:59,代码来源:integration_tests.py

示例9: _do_create_account

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def _do_create_account(post_vars):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
    user = User(username=post_vars['username'],
                email=post_vars['email'],
                is_active=False)
    user.set_password(post_vars['password'])
    registration = Registration()
    # TODO: Rearrange so that if part of the process fails, the whole process fails.
    # Right now, we can have e.g. no registration e-mail sent out and a zombie
    # account
    try:
        user.save()
    except IntegrityError:
        js = {'success': False}
        # Figure out the cause of the integrity error
        if len(User.objects.filter(username=post_vars['username'])) > 0:
            js['value'] = "An account with the Public Username  '" + post_vars[
                'username'] + "' already exists."
            js['field'] = 'username'
            return HttpResponse(json.dumps(js))

        if len(User.objects.filter(email=post_vars['email'])) > 0:
            js['value'] = "An account with the Email '" + post_vars[
                'email'] + "' already exists."
            js['field'] = 'email'
            return HttpResponse(json.dumps(js))

        raise

    registration.register(user)

    profile = UserProfile(user=user)
    profile.name = post_vars['name']
    profile.level_of_education = post_vars.get('level_of_education')
    profile.gender = post_vars.get('gender')
    profile.mailing_address = post_vars.get('mailing_address')
    profile.goals = post_vars.get('goals')

    try:
        profile.year_of_birth = int(post_vars['year_of_birth'])
    except (ValueError, KeyError):
        # If they give us garbage, just ignore it instead
        # of asking them to put an integer.
        profile.year_of_birth = None
    try:
        profile.save()
    except Exception:
        log.exception(
            "UserProfile creation failed for user {0}.".format(user.id))
    return (user, profile, registration)
开发者ID:hughdbrown,项目名称:edx-platform,代码行数:59,代码来源:views.py

示例10: new_user_social

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def new_user_social(request):
    if not request.user.is_authenticated():

        return HttpResponseRedirect('signin')
    try:
        userprofile=UserProfile(user=request.user)
        userprofile.save()
    except:
        return JsonResponse({"error": _("malformed JSON")}, 400)

    return HttpResponseRedirect('howitworks')
开发者ID:ngocchung75,项目名称:edx-platform,代码行数:13,代码来源:user.py

示例11: new_user_social

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def new_user_social(request):
    if not request.user.is_authenticated():

        return HttpResponseRedirect('signin')
    try:
        userprofile=UserProfile(user=request.user)
        userprofile.save()
    except:
        pass

    return index(request)
开发者ID:Mtax,项目名称:MHST2013-14,代码行数:13,代码来源:user.py

示例12: create_user

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def create_user(username,password,email,name):
        user = User(username=username,
                email=email,
                is_active=True,
                )
        user.set_password(password)
        user.save()
        registration = Registration()
        registration.register(user)
        profile = UserProfile(user=user)
        profile.name = name
        profile.save()
开发者ID:eduStack,项目名称:edx_siteapi,代码行数:14,代码来源:create_users.py

示例13: setUp

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
    def setUp(self):
        self.reset_setting_cache_variables()
        super(SelfPacedDateOverrideTest, self).setUp()

        SelfPacedConfiguration(enabled=True).save()

        self.non_staff_user, __ = self.create_non_staff_user()

        # create a UserProfile for user so user doesn't look like sneak_peek user
        nonstaff_user_profile = UserProfile(user=self.non_staff_user)
        nonstaff_user_profile.save()

        self.now = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
        self.future = self.now + datetime.timedelta(days=30)
开发者ID:stvstnfrd,项目名称:edx-platform,代码行数:16,代码来源:test_self_paced_overrides.py

示例14: setUp

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
    def setUp(self):
        """
        Create one user and save it to the database
        """
        self.user = UserFactory.build(username='test', email='[email protected]')
        self.user.set_password('test_password')
        self.user.save()
        profile = UserProfile(user=self.user)
        profile.city = 'Boston'
        profile.save()

        # Create the test client
        self.client = Client()
        cache.clear()
        self.session_url = '/api/server/sessions'
开发者ID:eduStack,项目名称:edx-serverapi,代码行数:17,代码来源:test_login_ratelimit.py

示例15: create_user_from_oauth

# 需要导入模块: from student.models import UserProfile [as 别名]
# 或者: from student.models.UserProfile import save [as 别名]
def create_user_from_oauth(strategy, details, user, is_new, *args, **kwargs):
    if is_new:
        profile = UserProfile(user=user)
        profile.name = details.get('fullname')

        try:
            profile.save()
        except Exception:
            log.error("UserProfile creation failed for user {id}.".format(id=user.id))
            raise

        ceas = CourseEnrollmentAllowed.objects.filter(email=user.email)
        for cea in ceas:
            if cea.auto_enroll:
                CourseEnrollment.enroll(user, cea.course_id)

        create_comments_service_user(user)
开发者ID:Certific-NET,项目名称:edx-platform,代码行数:19,代码来源:pipeline.py


注:本文中的student.models.UserProfile.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。