本文整理汇总了Python中student.models.UserProfile类的典型用法代码示例。如果您正苦于以下问题:Python UserProfile类的具体用法?Python UserProfile怎么用?Python UserProfile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UserProfile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: make_student
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,代码行数:34,代码来源:tests.py
示例2: create_lti_user
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,代码行数:35,代码来源:users.py
示例3: setUp
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,代码行数:28,代码来源:tests.py
示例4: import_user_submit
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,代码行数:58,代码来源:views.py
示例5: _do_create_account
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,代码行数:57,代码来源:views.py
示例6: import_user_submit
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,代码行数:57,代码来源:views.py
示例7: make_student
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,代码行数:57,代码来源:integration_tests.py
示例8: new_user_social
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,代码行数:11,代码来源:user.py
示例9: new_user_social
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,代码行数:11,代码来源:user.py
示例10: create_user
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,代码行数:12,代码来源:create_users.py
示例11: setUp
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,代码行数:14,代码来源:test_self_paced_overrides.py
示例12: user_submit
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,代码行数:30,代码来源:views.py
示例13: setUp
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,代码行数:15,代码来源:test_login_ratelimit.py
示例14: can_load
def can_load():
"""
NOTE: This does not check that the student is enrolled in the course
that contains this module. We may or may not want to allow non-enrolled
students to see modules. If not, views should check the course, so we
don't have to hit the enrollments table on every module load.
"""
# Stanford Sneak Peek permissions
if user.is_authenticated():
if not UserProfile.has_registered(user):
if not _can_load_descriptor_nonregistered(descriptor):
return ACCESS_DENIED
# / Stanford Sneak Peek permissions
if _has_staff_access_to_descriptor(user, descriptor, course_key):
return ACCESS_GRANTED
# if the user has staff access, they can load the module so this code doesn't need to run
return (
_visible_to_nonstaff_users(descriptor) and
_can_access_descriptor_with_milestones(user, descriptor, course_key) and
_has_group_access(descriptor, user, course_key) and
(
_has_detached_class_tag(descriptor) or
_can_access_descriptor_with_start_date(user, descriptor, course_key)
)
)
开发者ID:caesar2164,项目名称:edx-platform,代码行数:27,代码来源:access.py
示例15: get_feedback_form_context
def get_feedback_form_context(request):
"""
Extract the submitted form fields to be used as a context for
feedback submission.
"""
context = {}
context["subject"] = request.POST["subject"]
context["details"] = request.POST["details"]
context["tags"] = dict(
[(tag, request.POST[tag]) for tag in ["issue_type", "course_id"] if request.POST.get(tag)]
)
context["additional_info"] = {}
if UserProfile.has_registered(request.user):
context["realname"] = request.user.profile.name
context["email"] = request.user.email
context["additional_info"]["username"] = request.user.username
else:
context["realname"] = request.POST["name"]
context["email"] = request.POST["email"]
for header, pretty in [("HTTP_REFERER", "Page"), ("HTTP_USER_AGENT", "Browser"), ("REMOTE_ADDR", "Client IP"),
("SERVER_NAME", "Host")]:
context["additional_info"][pretty] = request.META.get(header)
context["support_email"] = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
return context
开发者ID:Stanford-Online,项目名称:edx-platform,代码行数:30,代码来源:views.py
示例16: can_load
def can_load():
"""
NOTE: This does not check that the student is enrolled in the course
that contains this module. We may or may not want to allow non-enrolled
students to see modules. If not, views should check the course, so we
don't have to hit the enrollments table on every module load.
"""
if user.is_authenticated():
if not UserProfile.has_registered(user):
if not _can_load_descriptor_nonregistered(descriptor):
return ACCESS_DENIED
response = (
_visible_to_nonstaff_users(descriptor)
and _has_group_access(descriptor, user, course_key)
and
(
_has_detached_class_tag(descriptor)
or _can_access_descriptor_with_start_date(user, descriptor, course_key)
)
)
return (
ACCESS_GRANTED if (response or _has_staff_access_to_descriptor(user, descriptor, course_key))
else response
)
开发者ID:caseylitton,项目名称:edx-platform,代码行数:25,代码来源:access.py
示例17: get_course_tab_list
def get_course_tab_list(request, course):
"""
Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
"""
user = request.user
is_user_enrolled = user.is_authenticated() and CourseEnrollment.is_enrolled(user, course.id)
xmodule_tab_list = CourseTabList.iterate_displayable(
course,
user=user,
settings=settings,
is_user_authenticated=user.is_authenticated(),
is_user_staff=has_access(user, 'staff', course, course.id),
is_user_enrolled=is_user_enrolled,
is_user_sneakpeek=not UserProfile.has_registered(user),
)
# Now that we've loaded the tabs for this course, perform the Entrance Exam work.
# If the user has to take an entrance exam, we'll need to hide away all but the
# "Courseware" tab. The tab is then renamed as "Entrance Exam".
course_tab_list = []
must_complete_ee = user_must_complete_entrance_exam(request, user, course)
for tab in xmodule_tab_list:
if must_complete_ee:
# Hide all of the tabs except for 'Courseware'
# Rename 'Courseware' tab to 'Entrance Exam'
if tab.type is not 'courseware':
continue
tab.name = _("Entrance Exam")
course_tab_list.append(tab)
# Add in any dynamic tabs, i.e. those that are not persisted
course_tab_list += _get_dynamic_tabs(course, user)
return course_tab_list
开发者ID:caseylitton,项目名称:edx-platform,代码行数:33,代码来源:tabs.py
示例18: get_course_tab_list
def get_course_tab_list(course, user):
"""
Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
"""
user_is_enrolled = user.is_authenticated() and CourseEnrollment.is_enrolled(user, course.id)
xmodule_tab_list = CourseTabList.iterate_displayable(
course,
settings,
user.is_authenticated(),
has_access(user, 'staff', course, course.id),
user_is_enrolled,
not UserProfile.has_registered(user),
)
# Now that we've loaded the tabs for this course, perform the Entrance Exam work
# If the user has to take an entrance exam, we'll need to hide away all of the tabs
# except for the Courseware and Instructor tabs (latter is only viewed if applicable)
# We don't have access to the true request object in this context, but we can use a mock
request = RequestFactory().request()
request.user = user
course_tab_list = []
for tab in xmodule_tab_list:
if user_must_complete_entrance_exam(request, user, course):
# Hide all of the tabs except for 'Courseware' and 'Instructor'
# Rename 'Courseware' tab to 'Entrance Exam'
if tab.type not in ['courseware', 'instructor']:
continue
if tab.type == 'courseware':
tab.name = _("Entrance Exam")
course_tab_list.append(tab)
return course_tab_list
开发者ID:dmohrC,项目名称:edx-platform,代码行数:31,代码来源:tabs.py
示例19: create_user_from_oauth
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,代码行数:17,代码来源:pipeline.py
示例20: make_student_module
def make_student_module(self, block, name, **state):
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()
self.addCleanup(profile.delete)
self.addCleanup(module.delete)
self.addCleanup(user.delete)
return module
开发者ID:bruce791130,项目名称:edx-sga,代码行数:17,代码来源:tests.py
注:本文中的student.models.UserProfile类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论