lms.djangoapps.courseware package#
Subpackages#
- lms.djangoapps.courseware.management package
- Subpackages
- lms.djangoapps.courseware.management.commands package
- Submodules
- lms.djangoapps.courseware.management.commands.clean_xml module
- lms.djangoapps.courseware.management.commands.dump_course_ids module
- lms.djangoapps.courseware.management.commands.dump_course_ids_with_filter module
- lms.djangoapps.courseware.management.commands.dump_course_structure module
- Module contents
- lms.djangoapps.courseware.management.commands package
- Module contents
- Subpackages
- lms.djangoapps.courseware.views package
- Submodules
- lms.djangoapps.courseware.views.index module
- lms.djangoapps.courseware.views.views module
BasePublicVideoXBlockViewCertDataCourseTabViewCourseTabView.course_open_for_learner_enrollment()CourseTabView.create_page_context()CourseTabView.get()CourseTabView.handle_exceptions()CourseTabView.register_user_access_warning_messages()CourseTabView.render_standalone_response()CourseTabView.render_to_fragment()CourseTabView.url_to_enroll()
EnrollStaffViewPerUserVideoMetadataThrottlePublicVideoXBlockEmbedViewPublicVideoXBlockViewPublicVideoXBlockView.build_url()PublicVideoXBlockView.dispatch()PublicVideoXBlockView.get_catalog_course_data()PublicVideoXBlockView.get_is_enrolled_in_course()PublicVideoXBlockView.get_learn_more_button_url()PublicVideoXBlockView.get_public_video_cta_button_urls()PublicVideoXBlockView.get_social_sharing_metadata()PublicVideoXBlockView.get_template_and_context()PublicVideoXBlockView.get_utm_params()
StaticCourseTabViewXBlockContentInspectorcourse_about()course_survey()courses()courseware_mfe_navigation_sidebar_toggles()courseware_mfe_search_enabled()credit_course_requirements()dates()enclosing_sequence_for_gating_checks()financial_assistance()financial_assistance_form()financial_assistance_request()financial_assistance_request_v2()generate_user_cert()get_cert_data()get_course_lti_endpoints()get_financial_aid_courses()get_learner_username()get_optimization_flags_for_content()get_static_tab_fragment()is_course_passed()jump_to()jump_to_id()load_metadata_from_youtube()program_marketing()progress()registered_for_course()render_xblock()submission_history()syllabus()user_groups()yt_video_metadata()
- Module contents
Submodules#
lms.djangoapps.courseware.access module#
This file contains (or should), all access control logic for the courseware. Ideally, it will be the only place that needs to know about any special settings like DISABLE_START_DATES.
- Note: The access control logic in this file does NOT check for enrollment in
a course. It is expected that higher layers check for enrollment so we don’t have to hit the enrollments table on every block load.
If enrollment is to be checked, use get_course_with_access in courseware.courses. It is a wrapper around has_access that additionally checks for enrollment.
- lms.djangoapps.courseware.access.administrative_accesses_to_course_for_user(user, course_key)#
Returns types of access a user have for given course.
- lms.djangoapps.courseware.access.get_user_role(user, course_key)#
Return corresponding string if user has staff, instructor or student course role in LMS.
- lms.djangoapps.courseware.access.has_access(user, action, obj, course_key=None)#
Check whether a user has the access to do action on obj. Handles any magic switching based on various settings.
Things this module understands: - start dates for blocks - visible_to_staff_only for blocks - DISABLE_START_DATES - different access for instructor, staff, course staff, and students. - mobile_available flag for course blocks
- user: a Django user object. May be anonymous. If none is passed,
anonymous is assumed
- obj: The object to check access for. A block, location, or
certain special strings (e.g. ‘global’)
action: A string specifying the action that the client is trying to perform.
actions depend on the obj type, but include e.g. ‘enroll’ for courses. See the type-specific functions below for the known actions for that type.
- course_key: A course_key specifying which course run this access is for.
Required when accessing anything other than a CourseBlock, ‘global’, or a location with category ‘course’
Returns an AccessResponse object. It is up to the caller to actually deny access in a way that makes sense in context.
- lms.djangoapps.courseware.access.has_ccx_coach_role(user, course_key)#
Check if user is a coach on this ccx.
- Parameters:
user (User) – the user whose course access we are checking.
course_key (CCXLocator) – Key to CCX.
- Returns:
whether user is a coach on this ccx or not.
- Return type:
bool
- lms.djangoapps.courseware.access.has_cms_access(user, course_key)#
Check if user has access to the CMS. When requesting from the LMS, a user with the limited staff access role needs access to the CMS APIs, but not the CMS site. This function accounts for this edge case when determining if a user has access to the CMS site.
- Parameters:
user (User) – the user whose course access we are checking.
course_key – Key to course.
- Returns:
whether user has access to the CMS site.
- Return type:
bool
- lms.djangoapps.courseware.access.has_staff_access_to_preview_mode(user, course_key)#
Checks if given user can access course in preview mode. A user can access a course in preview mode only if User has staff access to course.
- lms.djangoapps.courseware.access.is_mobile_available_for_user(user, block)#
Returns whether the given course is mobile_available for the given user. Checks:
mobile_available flag on the course Beta User and staff access overrides the mobile_available flag
- Parameters:
block (CourseBlock|CourseOverview) – course or overview of course in question
lms.djangoapps.courseware.access_response module#
This file contains all the classes used by has_access for error handling
- class lms.djangoapps.courseware.access_response.AccessError(error_code, developer_message, user_message, additional_context_user_message=None, user_fragment=None)#
Bases:
AccessResponseClass that holds information about the error in the case of an access denial in has_access. Contains the error code, user and developer messages. Subclasses represent specific errors.
- class lms.djangoapps.courseware.access_response.AccessResponse(has_access, error_code=None, developer_message=None, user_message=None, additional_context_user_message=None, user_fragment=None)#
Bases:
objectClass that represents a response from a has_access permission check.
- to_json()#
Creates a serializable JSON representation of an AccessResponse object.
- Returns:
JSON representation
- Return type:
dict
- class lms.djangoapps.courseware.access_response.AuthenticationRequiredAccessError#
Bases:
AccessErrorAccess denied because the user must be authenticated to see it
- class lms.djangoapps.courseware.access_response.CatalogVisibilityError#
Bases:
AccessErrorAccess denied because the course’s catalog_visibility setting prevents the user from seeing this course.
- class lms.djangoapps.courseware.access_response.DataSharingConsentRequiredAccessError(consent_url)#
Bases:
AccessErrorAccess denied because the user must give Data sharing consent before access it.
- class lms.djangoapps.courseware.access_response.EnrollmentRequiredAccessError#
Bases:
AccessErrorAccess denied because the user must be enrolled in the course
- class lms.djangoapps.courseware.access_response.IncorrectActiveEnterpriseAccessError(enrollment_enterprise_name, active_enterprise_name)#
Bases:
AccessErrorAccess denied because the user must login with correct enterprise.
- class lms.djangoapps.courseware.access_response.IncorrectPartitionGroupError(partition, user_group, allowed_groups, user_message=None, user_fragment=None)#
Bases:
AccessErrorAccess denied because the user is not in the correct user subset.
- class lms.djangoapps.courseware.access_response.MilestoneAccessError#
Bases:
AccessErrorAccess denied because the user has unfulfilled milestones
- class lms.djangoapps.courseware.access_response.MobileAvailabilityError#
Bases:
AccessErrorAccess denied because the course is not available on mobile for the user
- class lms.djangoapps.courseware.access_response.NoAllowedPartitionGroupsError(partition, user_message=None, user_fragment=None)#
Bases:
AccessErrorAccess denied because the content is not allowed to any group in a partition.
- class lms.djangoapps.courseware.access_response.OldMongoAccessError(courselike)#
Bases:
AccessErrorAccess denied because the course is in Old Mongo and we no longer support them. See DEPR-58.
- class lms.djangoapps.courseware.access_response.StartDateEnterpriseLearnerError(start_date, display_error_to_user=True)#
Bases:
AccessErrorAccess denied because the course has not started yet and the user is not staff. Use this error when this user is also an enterprise learner and enrolled in the requested course.
- class lms.djangoapps.courseware.access_response.StartDateError(start_date, display_error_to_user=True)#
Bases:
AccessErrorAccess denied because the course has not started yet and the user is not staff
- class lms.djangoapps.courseware.access_response.VisibilityError(display_error_to_user=True)#
Bases:
AccessErrorAccess denied because the user does not have the correct role to view this course.
lms.djangoapps.courseware.access_utils module#
Simple utility functions for computing access. It allows us to share code between access.py and block transformers.
- lms.djangoapps.courseware.access_utils.adjust_start_date(user, days_early_for_beta, start, course_key)#
If user is in a beta test group, adjust the start date by the appropriate number of days.
- Returns:
A datetime. Either the same as start, or earlier for beta testers.
- lms.djangoapps.courseware.access_utils.check_authentication(user, course)#
Grants access if the user is authenticated, or if the course allows public access.
- Returns:
Either ACCESS_GRANTED or AuthenticationRequiredAccessError
- Return type:
- lms.djangoapps.courseware.access_utils.check_correct_active_enterprise_customer(user, course_id)#
Grants access if the user’s active enterprise customer is same as EnterpriseCourseEnrollment’s Enterprise. Also, Grant access if enrollment is not Enterprise
- Returns:
Either ACCESS_GRANTED or IncorrectActiveEnterpriseAccessError
- Return type:
- lms.djangoapps.courseware.access_utils.check_course_open_for_learner(user, course)#
Check if the course is open for learners based on the start date.
- Returns:
Either ACCESS_GRANTED or StartDateError.
- Return type:
- lms.djangoapps.courseware.access_utils.check_data_sharing_consent(course_id)#
Grants access if the user is do not need DataSharing consent, otherwise returns data sharing link.
- Returns:
Either ACCESS_GRANTED or DataSharingConsentRequiredAccessError
- Return type:
- lms.djangoapps.courseware.access_utils.check_enrollment(user, course)#
Check if the course requires a learner to be enrolled for access.
- Returns:
Either ACCESS_GRANTED or EnrollmentRequiredAccessError.
- Return type:
- lms.djangoapps.courseware.access_utils.check_public_access(course, visibilities)#
This checks if the unenrolled access waffle flag for the course is set and the course visibility matches any of the input visibilities.
The “visibilities” argument is one of these constants from xmodule.course_block: - COURSE_VISIBILITY_PRIVATE - COURSE_VISIBILITY_PUBLIC - COURSE_VISIBILITY_PUBLIC_OUTLINE
- Returns:
Either ACCESS_GRANTED or ACCESS_DENIED.
- Return type:
- lms.djangoapps.courseware.access_utils.check_start_date(user, days_early_for_beta, start, course_key, display_error_to_user=True, now=None)#
Verifies whether the given user is allowed access given the start date and the Beta offset for the given course.
- Parameters:
display_error_to_user – If True, display this error to users in the UI.
- Returns:
Either ACCESS_GRANTED or StartDateError.
- Return type:
- lms.djangoapps.courseware.access_utils.debug(*args, **kwargs)#
Helper function for local debugging.
- lms.djangoapps.courseware.access_utils.enterprise_learner_enrolled(request, user, course_key)#
Determine if the learner should be redirected to the enterprise learner portal by checking their enterprise memberships/enrollments. If all of the following are true, then we are safe to redirect the learner:
The learner is linked to an enterprise customer,
The enterprise customer has subsidized the learner’s enrollment in the requested course,
The enterprise customer has the learner portal enabled.
NOTE: This function MUST be called from a view, or it will throw an exception.
- Parameters:
request (django.http.HttpRequest) – The current request being handled. Must not be None.
user (User) – The requesting enter, potentially an enterprise learner.
course_key (str) – The requested course to check for enrollment.
- Returns:
True if the learner is enrolled via a linked enterprise customer and can safely be redirected to the enterprise learner dashboard.
- Return type:
bool
- lms.djangoapps.courseware.access_utils.is_priority_access_error(access_error)#
Check if given access error is a priority Access Error or not. Priority Access Error can not be bypassed by staff users.
lms.djangoapps.courseware.block_render module#
Block rendering
- exception lms.djangoapps.courseware.block_render.LmsModuleRenderError#
Bases:
ExceptionAn exception class for exceptions thrown by block_render that don’t fit well elsewhere
- lms.djangoapps.courseware.block_render.append_data_to_webob_response(response, data)#
Appends data to a JSON webob response.
- Parameters:
response (webob response object) – the webob response object that needs to be modified
data (dict) – dictionary containing data that needs to be appended to response body
- Returns:
webob response with updated body.
- Return type:
(webob response object)
- lms.djangoapps.courseware.block_render.display_access_messages(user, block, view, frag, context)#
An XBlock wrapper that replaces the content fragment with a fragment or message determined by the has_access check.
- lms.djangoapps.courseware.block_render.get_block(user, request, usage_key, field_data_cache, position=None, log_if_not_found=True, wrap_xblock_display=True, grade_bucket_type=None, depth=0, static_asset_path='', course=None, will_recheck_access=False)#
Get an instance of the XBlock class identified by location, setting the state based on an existing StudentModule, or creating one if none exists.
- Parameters:
user (-) – User for whom we’re getting the block
request (-) – current django HTTPrequest. Note: request.user isn’t used for anything–all auth and such works based on user.
usage_key (-) – A UsageKey object identifying the module to load
field_data_cache (-) – a FieldDataCache
position (-) – Extra information from URL for user-specified position within module. It is used to determine the active tab within the SequenceBlock/subsection. Once the legacy course experience is removed, it should be safe to remove this, too.
log_if_not_found (-) – If this is True, we log a debug message if we cannot find the requested xmodule.
wrap_xblock_display (-) – If this is True, wrap the output display in a single div to allow for the XModule javascript to be bound correctly
depth (-) – number of levels of descendents to cache when loading this module. None means cache all descendents
static_asset_path (-) – static asset path to use (overrides block’s value); needed by get_course_info_section, because info section modules do not have a course as the parent module, and thus do not inherit this lms key value.
will_recheck_access (-) – If True, the caller commits to re-checking access on each child XBlock before rendering the content in order to display access error messages to the user.
Returns: XBlock instance, or None if the user does not have access to the block. If there’s an error, will try to return an instance of ErrorBlock if possible. If not possible, return None.
- lms.djangoapps.courseware.block_render.get_block_by_usage_id(request, course_id, usage_id, disable_staff_debug_info=False, course=None, will_recheck_access=False)#
Gets a block instance based on its usage_id in a course, for a given request/user
Returns (instance, tracking_context)
- lms.djangoapps.courseware.block_render.get_block_for_descriptor(user: User | AnonymousUser, request: Request | None, block: XBlock, field_data_cache: FieldDataCache | None, course_key: CourseKey, position: int | None = None, wrap_xblock_display: bool = True, grade_bucket_type: str | None = None, static_asset_path: str = '', disable_staff_debug_info: bool = False, course: CourseBlock | None = None, will_recheck_access: bool = False, track_function: Callable[[str, dict], None] | None = None, student_data: KvsFieldData | None = None, request_token: str | None = None, user_location: str | None = None) XBlock | None#
Implements get_block, extracting out the request-specific functionality.
disable_staff_debug_info : If this is True, exclude staff debug information in the rendering of the block.
See get_block() docstring for further details.
- lms.djangoapps.courseware.block_render.handle_xblock_callback(request, course_id, usage_id, handler, suffix=None)#
Generic view for extensions. This is where AJAX calls go.
- Parameters:
request (Request) – Django request.
course_id (str) – Course containing the block
usage_id (str)
handler (str)
suffix (str)
- Raises:
HttpResponseForbidden – If the request method is not GET and user is not authenticated.
Http404 – If the course is not found in the modulestore.
- lms.djangoapps.courseware.block_render.handle_xblock_callback_noauth(request, course_id, usage_id, handler, suffix=None)#
Entry point for unauthenticated XBlock handlers.
- lms.djangoapps.courseware.block_render.load_single_xblock(request, user_id, course_id, usage_key_string, course=None, will_recheck_access=False)#
Load a single XBlock identified by usage_key_string.
- lms.djangoapps.courseware.block_render.make_track_function(request)#
Make a tracking function that logs what happened. For use in ModuleStoreRuntime.
- lms.djangoapps.courseware.block_render.prepare_runtime_for_user(user: User | AnonymousUser, student_data: KvsFieldData, runtime: Runtime, course_id: CourseKey, track_function: Callable[[str, dict], None], request_token: str, position: int | None = None, wrap_xblock_display: bool = True, grade_bucket_type: str | None = None, static_asset_path: str = '', user_location: str | None = None, disable_staff_debug_info: bool = False, course: CourseBlock | None = None, will_recheck_access: bool = False)#
Helper function that binds the given xblock to a user and student_data to a user and the block.
The purpose of this function is to factor out everywhere a user is implicitly bound when creating a module, to allow an existing block to be re-bound to a user.
The arguments fall into two categories: those that have explicit or implicit user binding, which are user and student_data, and those don’t and are used to instantiate the service required in LMS, which are all the other arguments.
- Parameters:
get_block() (see arguments for)
request_token (str) – A token unique to the request use by xblock initialization
- lms.djangoapps.courseware.block_render.toc_for_course(user, request, course, active_chapter, active_section, field_data_cache)#
Create a table of contents from the module store
Return format: { ‘chapters’: [
{‘display_name’: name, ‘url_name’: url_name, ‘sections’: SECTIONS, ‘active’: bool},
], ‘previous_of_active_section’: {..}, ‘next_of_active_section’: {..}
}
where SECTIONS is a list [ {‘display_name’: name, ‘url_name’: url_name,
‘format’: format, ‘due’: due, ‘active’ : bool, ‘graded’: bool}, …]
where previous_of_active_section and next_of_active_section have information on the next/previous sections of the active section.
active is set for the section and chapter corresponding to the passed parameters, which are expected to be url_names of the chapter+section. Everything else comes from the xml, or defaults to “”.
chapters with name ‘hidden’ are skipped.
NOTE: assumes that if we got this far, user has access to course. Returns None if this is not the case.
field_data_cache must include data from the course blocks and 2 levels of its descendants
- lms.djangoapps.courseware.block_render.xblock_view(request, *args, **kwargs)#
Returns the rendered view of a given XBlock, with related resources
- Returns a json object containing two keys:
html: The rendered html of the view resources: A list of tuples where the first element is the resource hash, and
the second is the resource description
- lms.djangoapps.courseware.block_render.xqueue_callback(request, course_id, userid, mod_id, dispatch)#
Entry point for graded results from the queueing system.
lms.djangoapps.courseware.config module#
Waffle flags and switches
lms.djangoapps.courseware.constants module#
Constants for courseware app.
lms.djangoapps.courseware.context_processor module#
This is the courseware context_processor module.
This is meant to simplify the process of sending user preferences (espec. time_zone and pref-lang) to the templates without having to append every view file.
- lms.djangoapps.courseware.context_processor.get_last_seen_courseware_timezone(user)#
The above method is for the timezone that is set on the user’s account. That timezone is often not set, so this field retrieves the browser timezone from a recent courseware visit (updated daily)
- lms.djangoapps.courseware.context_processor.get_user_timezone_or_last_seen_timezone_or_utc(user)#
Helper method for returning a reasonable timezone for a user. This method returns the timezone in the user’s account if that is set. If that is not set, it returns a recent timezone that we have recorded from a user’s visit to the courseware. If that is not set or the timezone is unknown, it returns UTC.
- lms.djangoapps.courseware.context_processor.user_timezone_locale_prefs(request)#
Checks if request has an authenticated user. If so, sends set (or none if unset) time_zone and language prefs. If site-wide language is set, that language is used over the language set in user preferences.
This interacts with the DateUtils to either display preferred or attempt to determine system/browser set time_zones and languages
lms.djangoapps.courseware.course_tools module#
Platform plugins to support course tools.
- class lms.djangoapps.courseware.course_tools.FinancialAssistanceTool#
Bases:
CourseToolThe financial assistance tool.
- classmethod analytics_id()#
Returns an id to uniquely identify this tool in analytics events.
- classmethod icon_classes(course_key=None)#
Returns the icon classes needed to represent this tool.
- classmethod is_enabled(request, course_key)#
Show this link for active courses where financial assistance is available, unless upgrade deadline has passed
- classmethod title(course_key=None)#
Returns the title of this tool.
- classmethod url(course_key)#
Returns the URL for this tool for the specified course key.
lms.djangoapps.courseware.courses module#
Functions for accessing and displaying courses within the courseware.
- lms.djangoapps.courseware.courses.can_self_enroll_in_course(course_key)#
Returns True if the user can enroll themselves in a course.
Note: an example of a course that a user cannot enroll in directly is a CCX course. For such courses, a user can only be enrolled by a CCX coach.
- lms.djangoapps.courseware.courses.check_course_access(course, user, action, check_if_enrolled=False, check_survey_complete=True, check_if_authenticated=False, apply_enterprise_checks=False)#
Check that the user has the access to perform the specified action on the course (CourseBlock|CourseOverview).
check_if_enrolled: If true, additionally verifies that the user is enrolled. check_survey_complete: If true, additionally verifies that the user has completed the survey.
- lms.djangoapps.courseware.courses.check_course_access_with_redirect(course, user, action, check_if_enrolled=False, check_survey_complete=True, check_if_authenticated=False, allow_not_started_courses=False)#
Check that the user has the access to perform the specified action on the course (CourseBlock|CourseOverview).
check_if_enrolled: If true, additionally verifies that the user is enrolled. check_survey_complete: If true, additionally verifies that the user has completed the survey.
- lms.djangoapps.courseware.courses.course_open_for_self_enrollment(course_key)#
For a given course_key, determine if the course is available for enrollment
- lms.djangoapps.courseware.courses.date_block_key_fn(block)#
If the block’s date is None, return the maximum datetime in order to force it to the end of the list of displayed blocks.
- lms.djangoapps.courseware.courses.find_file(filesystem, dirs, filename)#
Looks for a filename in a list of dirs on a filesystem, in the specified order.
filesystem: an OSFS filesystem dirs: a list of path objects filename: a string
Returns d / filename if found in dir d, else raises ResourceNotFound.
- lms.djangoapps.courseware.courses.get_assignments_completions(course_key, user)#
Calculate the progress of the user in the course by assignments.
- Parameters:
course_key (CourseLocator) – The Course for which course progress is requested.
user (User) – The user for whom course progress is requested.
- Returns:
- Dictionary contains information about total assignments count
in the given course and how many assignments the user has completed.
- Return type:
dict (dict)
- lms.djangoapps.courseware.courses.get_assignments_grades(user, course_id, cache_timeout)#
Calculate the progress of the assignment for the user in the course.
- Parameters:
user (User) – Django User object.
course_id (CourseLocator) – The course key.
cache_timeout (int) – Cache timeout in seconds
- Returns:
list[Union[ReadSubsectionGrade, ZeroSubsectionGrade]]: List of subsection grades.
list[dict]: List of dictionaries with section-level grade breakdown and assignment info.
- Return type:
tuple
- lms.djangoapps.courseware.courses.get_cms_block_link(block, page)#
Returns a link to block_index for editing the course in cms, assuming that the block is actually cms-backed.
- lms.djangoapps.courseware.courses.get_cms_course_link(course, page='course')#
Returns a link to course_index for editing the course in cms, assuming that the course is actually cms-backed.
- lms.djangoapps.courseware.courses.get_course(course_id, depth=0)#
Given a course id, return the corresponding course block.
If the course does not exist, raises a CourseRunNotFound. This is appropriate for internal use.
depth: The number of levels of children for the modulestore to cache. None means infinite depth. Default is to fetch no children.
- lms.djangoapps.courseware.courses.get_course_about_section(request, course, section_key)#
This returns the snippet of html to be rendered on the course about page, given the key for the section.
Valid keys: - overview - about_sidebar_html - short_description - description - key_dates (includes start, end, exams, etc) - video - course_staff_short - course_staff_extended - requirements - syllabus - textbook - faq - effort - more_info - ocw_links
- lms.djangoapps.courseware.courses.get_course_assignment_date_blocks(course, user, request, num_return=None, include_past_dates=False, include_access=False)#
Returns a list of assignment (at the subsection/sequential level) due date blocks for the given course. Will return num_return results or all results if num_return is None in date increasing order.
- lms.djangoapps.courseware.courses.get_course_assignments(course_key, user, include_access=False, include_without_due=False)#
Returns a list of assignment (at the subsection/sequential level) due dates for the given course.
Each returned object is a namedtuple with fields: title, url, date, contains_gated_content, complete, past_due, assignment_type
- lms.djangoapps.courseware.courses.get_course_blocks_completion_summary(course_key, user)#
Returns an object with the number of complete units, incomplete units, and units that contain gated content for the given course. The complete and incomplete counts only reflect units that are able to be completed by the given user. If a unit contains gated content, it is not counted towards the incomplete count.
The object contains fields: complete_count, incomplete_count, locked_count
- lms.djangoapps.courseware.courses.get_course_chapter_ids(course_key)#
Extracts the chapter block keys from a course structure.
- Parameters:
course_key (CourseLocator) – The course key
- Returns:
The list of string representations of the chapter block keys in the course.
- Return type:
list (string)
- lms.djangoapps.courseware.courses.get_course_date_blocks(course, user, request=None, include_access=False, include_past_dates=False, num_assignments=None)#
Return the list of blocks to display on the course info page, sorted by date.
- lms.djangoapps.courseware.courses.get_course_info_section(request, user, course, section_key)#
This returns the snippet of html to be rendered on the course info page, given the key for the section.
Valid keys: - handouts - guest_handouts - updates - guest_updates
- lms.djangoapps.courseware.courses.get_course_info_section_block(request, user, course, section_key)#
This returns the course info block for a given section_key.
Valid keys: - handouts - guest_handouts - updates - guest_updates
- lms.djangoapps.courseware.courses.get_course_info_usage_key(course, section_key)#
Returns the usage key for the specified section’s course info block.
- lms.djangoapps.courseware.courses.get_course_overview_with_access(user, action, course_key, check_if_enrolled=False)#
Given a course_key, look up the corresponding course overview, check that the user has the access to perform the specified action on the course, and return the course overview.
Raises a 404 if the course_key is invalid, or the user doesn’t have access.
- check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
or has staff access.
- lms.djangoapps.courseware.courses.get_course_syllabus_section(course, section_key)#
This returns the snippet of html to be rendered on the syllabus page, given the key for the section.
Valid keys: - syllabus - guest_syllabus
- lms.djangoapps.courseware.courses.get_course_with_access(user, action, course_key, depth=0, check_if_enrolled=False, check_survey_complete=True, check_if_authenticated=False, allow_not_started_courses=False)#
Given a course_key, look up the corresponding course block, check that the user has the access to perform the specified action on the course, and return the block.
Raises a 404 if the course_key is invalid, or the user doesn’t have access.
depth: The number of levels of children for the modulestore to cache. None means infinite depth
- check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
or has staff access.
- check_survey_complete: If true, additionally verifies that the user has either completed the course survey
or has staff access. Note: We do not want to continually add these optional booleans. Ideally, these special cases could not only be handled inside has_access, but could be plugged in as additional callback checks for different actions.
- lms.djangoapps.courseware.courses.get_courses(user, org=None, filter_=None, permissions=None, active_only=False, course_keys=None)#
Return a LazySequence of courses available, optionally filtered by org code (case-insensitive) or a set of permissions to be satisfied for the specified user.
- lms.djangoapps.courseware.courses.get_current_child(xblock, min_depth=None, requested_child=None)#
Get the xblock.position’s display item of an xblock that has a position and children. If xblock has no position or is out of bounds, return the first child with children of min_depth.
For example, if chapter_one has no position set, with two child sections, section-A having no children and section-B having a discussion unit, get_current_child(chapter, min_depth=1) will return section-B.
Returns None only if there are no children at all.
- lms.djangoapps.courseware.courses.get_first_component_of_block(block_key, block_data)#
This function returns the first leaf block of a section(block_key)
- lms.djangoapps.courseware.courses.get_ora_as_assignments(block_data, ora_block)#
Given an individual ORA, return the list of individual ORA steps as Assignment tuples
- lms.djangoapps.courseware.courses.get_ora_blocks_as_assignments(block_data, subsection_key)#
Given a subsection key, navigate through descendents and find open response assessments. For each graded ORA, return a list of “Assignment” tuples that map to the individual steps of the ORA
- lms.djangoapps.courseware.courses.get_past_and_future_course_assignments(request, user, course)#
Returns the future assignment data and past assignments data for given user and course.
- Parameters:
- Returns:
- Tuple of past_assignments list and next_assignments list.
next_assignments list contains only uncompleted assignments.
- Return type:
tuple (list, list)
- lms.djangoapps.courseware.courses.get_permission_for_course_about()#
Returns the CourseOverview object for the course after checking for access.
- lms.djangoapps.courseware.courses.get_problems_in_section(section)#
This returns a dict having problems in a section. Returning dict has problem location as keys and problem block as values.
- lms.djangoapps.courseware.courses.get_studio_url(course, page)#
Get the Studio URL of the page that is passed in.
- Parameters:
course (CourseBlock)
- lms.djangoapps.courseware.courses.sort_by_announcement(courses)#
Sorts a list of courses by their announcement date. If the date is not available, sort them by their start date.
- lms.djangoapps.courseware.courses.sort_by_start_date(courses)#
Returns a list of courses sorted by their start date, latest first.
lms.djangoapps.courseware.courseware_access_exception module#
This file contains the exception used in courseware access
lms.djangoapps.courseware.date_summary module#
This module provides date summary blocks for the Course Info page. Each block gives information about a particular course-run-specific date which will be displayed to the user.
- class lms.djangoapps.courseware.date_summary.CertificateAvailableDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the certificate available date of the course.
- css_class = 'certificate-available-date'#
- property date#
This summary’s date.
- property date_type#
- property description#
The detail text displayed by this summary.
- property has_certificate_modes#
- is_allowed()#
Whether or not this summary block is applicable or active for its course.
For example, a DateSummary might only make sense for a self-paced course, and you could restrict it here.
You should not make time-sensitive checks here. That sort of thing belongs in is_enabled.
- title = 'Certificate Available'#
- class lms.djangoapps.courseware.date_summary.CourseAssignmentDate(*args, **kwargs)#
Bases:
DateSummaryDisplays due dates for homework assignments with a link to the homework assignment if the link is provided.
- css_class = 'assignment'#
- property date#
This summary’s date.
- property date_type#
- property extra_info#
Extra detail to display as a tooltip.
- property link#
The location to link to for more information.
- set_title(title, link=None)#
Used to set the title_html and title properties for the assignment date block
- property title#
The title of this summary.
- property title_html#
The title as html for this summary.
- class lms.djangoapps.courseware.date_summary.CourseEndDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the end date of the course.
- css_class = 'end-date'#
- property date#
Returns the course end date, if applicable. For self-paced courses using Personalized Learner Schedules, the end date is only displayed if it is within 365 days.
- property date_type#
- property description#
Returns a description for what experience changes a learner encounters when the course end date passes. Note that this currently contains 4 scenarios:
End date is in the future and learner is enrolled in a certificate earning mode
- End date is in the future and learner is not enrolled at all or not enrolled
in a certificate earning mode
End date is in the past
End date does not exist (and now neither does the description)
- is_enabled = True#
- title = 'Course ends'#
- class lms.djangoapps.courseware.date_summary.CourseExpiredDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the course expiration date for Audit learners (if enabled)
- css_class = 'course-expired'#
- property date#
This summary’s date.
- property date_type#
- property description#
The detail text displayed by this summary.
- is_allowed()#
Whether or not this summary block is applicable or active for its course.
For example, a DateSummary might only make sense for a self-paced course, and you could restrict it here.
You should not make time-sensitive checks here. That sort of thing belongs in is_enabled.
- property title#
The title of this summary.
- class lms.djangoapps.courseware.date_summary.CourseStartDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the start date of the course.
- css_class = 'start-date'#
- property date#
This summary’s date.
- property date_type#
- property title#
The title of this summary.
- class lms.djangoapps.courseware.date_summary.DateSummary(course, user, course_id=None)#
Bases:
objectBase class for all date summary blocks.
- property css_class#
The CSS class of this summary. Indicates the type of information this summary block contains, and its urgency.
- property current_time#
Returns a consistent current time.
- property date#
This summary’s date.
- property date_format#
The format to display this date in. By default, displays like Jan 01, 2015.
- date_html(date_format='shortDate')#
Returns a representation of the date as HTML.
Note: this returns a span that will be localized on the client.
- property date_type#
- deadline_has_passed()#
Return True if a deadline (the date) exists, and has already passed. Returns False otherwise.
- property description#
The detail text displayed by this summary.
- property extra_info#
Extra detail to display as a tooltip.
- is_allowed()#
Whether or not this summary block is applicable or active for its course.
For example, a DateSummary might only make sense for a self-paced course, and you could restrict it here.
You should not make time-sensitive checks here. That sort of thing belongs in is_enabled.
- property is_enabled#
Whether or not this summary block should be shown.
By default, the summary is only shown if its date is in the future.
- property link#
The location to link to for more information.
- property link_text#
The text of the link.
- property long_date_html#
Returns a long representation of the date as HTML.
Note: this returns a span that will be localized on the client.
- property relative_datestring#
Return this block’s date in a human-readable format. If the date is None, returns the empty string.
- property short_time_html#
Returns a short representation of the time as HTML.
Note: this returns a span that will be localized on the client.
- property time_remaining_string#
Returns the time remaining as a localized string.
- property title#
The title of this summary.
- property title_html#
The title as html for this summary.
- class lms.djangoapps.courseware.date_summary.TodaysDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays today’s date.
- css_class = 'todays-date'#
- property date#
This summary’s date.
- property date_type#
- get_context()#
- is_enabled = True#
- property title#
The title of this summary.
- class lms.djangoapps.courseware.date_summary.VerificationDeadlineDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the date by which the user must complete the verification process.
- property css_class#
The CSS class of this summary. Indicates the type of information this summary block contains, and its urgency.
- date()#
This summary’s date.
- property date_type#
- property description#
The detail text displayed by this summary.
- is_allowed()#
Whether or not this summary block is applicable or active for its course.
For example, a DateSummary might only make sense for a self-paced course, and you could restrict it here.
You should not make time-sensitive checks here. That sort of thing belongs in is_enabled.
- is_enabled = True#
- property link#
The location to link to for more information.
- property link_table#
Maps verification state to a tuple of link text and location.
- property link_text#
The text of the link.
- must_retry()#
Return True if the user must re-submit verification, False otherwise.
- property title#
The title of this summary.
- verification_status()#
Return the verification status for this user.
- class lms.djangoapps.courseware.date_summary.VerifiedUpgradeDeadlineDate(course, user, course_id=None)#
Bases:
DateSummaryDisplays the date before which learners must upgrade to the Verified track.
- css_class = 'verified-upgrade-deadline'#
- date()#
This summary’s date.
- property date_type#
- property description#
The detail text displayed by this summary.
- enrollment#
- is_allowed()#
Whether or not this summary block is applicable or active for its course.
For example, a DateSummary might only make sense for a self-paced course, and you could restrict it here.
You should not make time-sensitive checks here. That sort of thing belongs in is_enabled.
- property link#
The location to link to for more information.
- link_text = 'Upgrade to Verified Certificate'#
- property relative_datestring#
Return this block’s date in a human-readable format. If the date is None, returns the empty string.
- property title#
The title of this summary.
lms.djangoapps.courseware.entrance_exams module#
This file contains all entrance exam related utils/logic.
- lms.djangoapps.courseware.entrance_exams.course_has_entrance_exam(course)#
Checks to see if a course is properly configured for an entrance exam
- lms.djangoapps.courseware.entrance_exams.get_entrance_exam_content(user, course)#
Get the entrance exam content information (ie, chapter block)
- lms.djangoapps.courseware.entrance_exams.user_can_skip_entrance_exam(user, course)#
Checks all of the various override conditions for a user to skip an entrance exam Begin by short-circuiting if the course does not have an entrance exam
- lms.djangoapps.courseware.entrance_exams.user_has_passed_entrance_exam(user, course)#
Checks to see if the user has attained a sufficient score to pass the exam Begin by short-circuiting if the course does not have an entrance exam
lms.djangoapps.courseware.exceptions module#
Exception classes used in lms/courseware.
- exception lms.djangoapps.courseware.exceptions.CourseAccessRedirect(url, access_error=None)#
Bases:
RedirectRedirect raised when user does not have access to a course.
- Parameters:
url (string) – The redirect url.
access_error (AccessErro) – The AccessError that caused the redirect. The AccessError contains messages for developers and users explaining why the user was denied access. These strings can then be exposed to the user.
- exception lms.djangoapps.courseware.exceptions.CourseRunNotFound(course_key)#
Bases:
ValueErrorIndicate that a supplied course run key does not map to a course run in the system.
- exception lms.djangoapps.courseware.exceptions.Redirect(url)#
Bases:
ExceptionException class that requires redirecting to a URL.
lms.djangoapps.courseware.field_overrides module#
This module provides a FieldData implementation
which wraps an other FieldData object and provides overrides based on the
user. The use of providers allows for overrides that are arbitrarily
extensible. One provider is found in lms.djangoapps.courseware.student_field_overrides
which allows for fields to be overridden for individual students. One can
envision other providers being written that allow for fields to be overridden
base on membership of a student in a cohort, or similar. The use of an
extensible, modular architecture allows for overrides being done in ways not
envisioned by the authors.
Currently, this module is used in the block_render module in this same package and is used to wrap the authored_data when constructing an LmsFieldData. This means overrides will be in effect for all scopes covered by authored_data, e.g. course content and settings stored in Mongo.
- class lms.djangoapps.courseware.field_overrides.FieldOverrideProvider(user, fallback_field_data)#
Bases:
objectAbstract class which defines the interface that a FieldOverrideProvider must provide. In general, providers should derive from this class, but it’s not strictly necessary as long as they correctly implement this interface.
A FieldOverrideProvider implementation is only responsible for looking up field overrides. To set overrides, there will be a domain specific API for the concrete override implementation being used.
- abstractmethod enabled_for(course)#
Return True if this provider should be enabled for a given course, and False otherwise.
Concrete implementations are responsible for implementing this method.
- Parameters:
course (CourseBlock or None)
- Returns:
bool
- abstractmethod get(block, name, default)#
Look for an override value for the field named name in block. Returns the overridden value or default if no override is found.
- class lms.djangoapps.courseware.field_overrides.OverrideFieldData(user, fallback, providers)#
Bases:
FieldDataA
FieldDatawhich wraps another FieldData object and allows for fields handled by the wrapped FieldData to be overriden by arbitrary providers.Providers are configured by use of the Django setting, FIELD_OVERRIDE_PROVIDERS which should be a tuple of dotted names of
FieldOverrideProviderconcrete implementations. Note that order is important for this setting. Override providers will tried in the order configured in the setting. The first provider to find an override ‘wins’ for a particular field lookup.- default(block, name)#
Get the default value for this field which may depend on context or may just be the field’s global default. The default behavior is to raise KeyError which will cause the caller to return the field’s global default.
- Parameters:
block (
XBlock) – the block containing the field being defaultedname (str) – the field’s name
- delete(block, name)#
Reset the value of the field named name to the default for XBlock block.
- Parameters:
block (
XBlock) – block to modifyname (str) – field name to delete
- get(block, name)#
Retrieve the value for the field named name for the XBlock block.
If no value is set, raise a KeyError.
The value returned may be mutated without modifying the backing store.
- Parameters:
block (
XBlock) – block to inspectname (str) – field name to look up
- get_override(block, name)#
Checks for an override for the field identified by name in block. Returns the overridden value or NOTSET if no override is found.
- has(block, name)#
Return whether or not the field named name has a non-default value for the XBlock block.
- Parameters:
block (
XBlock) – block to checkname (str) – field name
- provider_classes = None#
- set(block, name, value)#
Set the value of the field named name for XBlock block.
value may be mutated after this call without affecting the backing store.
- Parameters:
block (
XBlock) – block to modifyname (str) – field name to set
value – value to set
- set_many(block, update_dict)#
Update many fields on an XBlock simultaneously.
- Parameters:
block (
XBlock) – the block to updateupdate_dict (dict) – A map of field names to their new values
- classmethod wrap(user, course, wrapped)#
Will return a
OverrideFieldDatawhich wraps the field data given in wrapped for the given user, if override providers are configred. If no override providers are configured, using the Django setting, FIELD_OVERRIDE_PROVIDERS, returns wrapped, eliminating any performance impact of this feature if no override providers are configured.
- class lms.djangoapps.courseware.field_overrides.OverrideModulestoreFieldData(fallback, providers)#
Bases:
OverrideFieldDataApply field data overrides at the modulestore level. No student context required.
- provider_classes = None#
- classmethod wrap(block, field_data)#
Returns an instance of FieldData wrapped by FieldOverrideProviders which extend read-only functionality. If no MODULESTORE_FIELD_OVERRIDE_PROVIDERS are configured, an unwrapped FieldData instance is returned.
- Parameters:
block – An XBlock
field_data – An instance of FieldData to be wrapped
- lms.djangoapps.courseware.field_overrides.disable_overrides()#
A context manager which disables field overrides inside the context of a with statement, allowing code to get at the original value of a field.
- lms.djangoapps.courseware.field_overrides.overrides_disabled()#
Checks to see whether overrides are disabled in the current context. Returns a boolean value. See disable_overrides.
- lms.djangoapps.courseware.field_overrides.resolve_dotted(name)#
Given the dotted name for a Python object, performs any necessary imports and returns the object.
lms.djangoapps.courseware.fields module#
Custom fields
- class lms.djangoapps.courseware.fields.UnsignedBigIntAutoField(*args, **kwargs)#
Bases:
AutoFieldAn unsigned 8-byte integer for auto-incrementing primary keys.
- db_type(connection)#
Return the database column data type for this field, for the provided connection.
- rel_db_type(connection)#
Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type.
lms.djangoapps.courseware.masquerade module#
—————————————- Masquerade —————————————- Allow course staff to see a student or staff view of courseware. Which kind of view has been selected is stored in the session state.
- class lms.djangoapps.courseware.masquerade.CourseMasquerade(course_key, role='student', user_partition_id=None, group_id=None, user_name=None)#
Bases:
objectMasquerade settings for a particular course.
- get_active_group_name(available)#
Lookup the active group name, from available options
- Returns: the corresponding group name, if exists,
else, return None
- class lms.djangoapps.courseware.masquerade.MasqueradeView(**kwargs)#
Bases:
ViewCreate an HTTP endpoint to manage masquerade settings
- dispatch(request, *args, **kwargs)#
- get(request, course_key_string)#
Retrieve data on the active and available masquerade options
- post(request, course_key_string)#
Handle AJAX posts to update the current user’s masquerade for the specified course. The masquerade settings are stored in the Django session as a dict from course keys to CourseMasquerade objects.
- class lms.djangoapps.courseware.masquerade.MasqueradingKeyValueStore(kvs, session)#
Bases:
KeyValueStoreA KeyValueStore to avoid affecting the user state when masquerading.
This KeyValueStore wraps an underlying KeyValueStore. Reads are forwarded to the underlying store, but writes go to a Django session (or other dictionary-like object).
- delete(key)#
Deletes key from storage.
- get(key)#
Reads the value of the given key from storage.
- has(key)#
Returns whether or not key is present in storage.
- set(key, value)#
Sets key equal to value in storage.
- lms.djangoapps.courseware.masquerade.check_content_start_date_for_masquerade_user(course_key, user, request, course_start, chapter_start=None, section_start=None)#
Add a warning message if the masquerade user would not have access to this content due to the content start date being in the future.
- lms.djangoapps.courseware.masquerade.filter_displayed_blocks(block, unused_view, frag, unused_context)#
A wrapper to only show XBlocks that set show_in_read_only_mode when masquerading as a specific user.
We don’t want to modify the state of the user we are masquerading as, so we can’t show XBlocks that store information outside of the XBlock fields API.
- lms.djangoapps.courseware.masquerade.get_course_masquerade(user, course_key)#
Returns the masquerade for the current user for the specified course. If no masquerade has been installed, then a default no-op masquerade is returned.
- lms.djangoapps.courseware.masquerade.get_masquerade_role(user, course_key)#
Returns the role that the user is masquerading as, or None if no masquerade is in effect.
- lms.djangoapps.courseware.masquerade.get_masquerading_user_group(course_key, user, user_partition)#
If the current user is masquerading as a generic learner in a specific group, return that group. If the user is not masquerading as a group, then None is returned.
- lms.djangoapps.courseware.masquerade.get_specific_masquerading_user(user, course_key)#
Return the specific user that a staff member is masquerading as, or None if they aren’t.
- lms.djangoapps.courseware.masquerade.is_masquerading(user, course_key, course_masquerade=None)#
Return if the user is masquerading at all
- lms.djangoapps.courseware.masquerade.is_masquerading_as_audit_enrollment(user, course_key, course_masquerade=None)#
Return if the user is a staff member masquerading as a user in the audit enrollment track
- lms.djangoapps.courseware.masquerade.is_masquerading_as_full_access(user, course_key, course_masquerade=None)#
Return if the user is a staff member masquerading as a user in the Full-Access track
- lms.djangoapps.courseware.masquerade.is_masquerading_as_limited_access(user, course_key, course_masquerade=None)#
Return if the user is a staff member masquerading as a user in the Limited-Access track
- lms.djangoapps.courseware.masquerade.is_masquerading_as_non_audit_enrollment(user, course_key, course_masquerade=None)#
Return if the user is a staff member masquerading as a user in _any_ enrollment track _except_ audit
- lms.djangoapps.courseware.masquerade.is_masquerading_as_specific_student(user, course_key)#
Returns whether the user is a staff member masquerading as a specific student.
- lms.djangoapps.courseware.masquerade.is_masquerading_as_staff(user, course_key)#
Return if the user is a staff member masquerading as user that is itself a staff user
- lms.djangoapps.courseware.masquerade.is_masquerading_as_student(user, course_key)#
Returns true if the user is a staff member masquerading as a student.
- lms.djangoapps.courseware.masquerade.setup_masquerade(request, course_key, staff_access=False, reset_masquerade_data=False)#
Sets up masquerading for the current user within the current request. The request’s user is updated to have a ‘masquerade_settings’ attribute with the dict of all masqueraded settings if called from within a request context. The function then returns a pair (CourseMasquerade, User) with the masquerade settings for the specified course key or None if there isn’t one, and the user we are masquerading as or request.user if masquerading as a specific user is not active.
If the reset_masquerade_data flag is set, the field data stored in the session will be cleared.
lms.djangoapps.courseware.middleware module#
Middleware for the courseware app
- class lms.djangoapps.courseware.middleware.CacheCourseIdMiddleware(get_response)#
Bases:
MiddlewareMixinMiddleware that adds course_id to user request session.
- process_request(request)#
Add a course_id to user request session.
- class lms.djangoapps.courseware.middleware.RedirectMiddleware(get_response)#
Bases:
MiddlewareMixinCatch Redirect exceptions and redirect the user to the expected URL.
- process_exception(_request, exception)#
Catch Redirect exceptions and redirect the user to the expected URL.
lms.djangoapps.courseware.model_data module#
Classes to provide the LMS runtime data storage to XBlocks.
DjangoKeyValueStore: An XBlockKeyValueStorewhichstores a subset of xblocks scopes as Django ORM objects. It wraps
FieldDataCacheto provide an XBlock-friendly interface.FieldDataCache: A object which provides a read-through prefetch cacheof data to support XBlock fields within a limited set of scopes.
The remaining classes in this module provide read-through prefetch cache implementations for specific scopes. The individual classes provide the knowledge of what are the essential pieces of information for each scope, and thus how to cache, prefetch, and create new field data entries.
UserStateCache: A cache for Scope.user_state UserStateSummaryCache: A cache for Scope.user_state_summary PreferencesCache: A cache for Scope.preferences UserInfoCache: A cache for Scope.user_info DjangoOrmFieldCache: A base-class for single-row-per-field caches.
- class lms.djangoapps.courseware.model_data.DjangoKeyValueStore(field_data_cache)#
Bases:
KeyValueStore- This KeyValueStore will read and write data in the following scopes to django models
Scope.user_state_summary Scope.user_state Scope.preferences Scope.user_info
Access to any other scopes will raise an InvalidScopeError
Data for Scope.user_state is stored as StudentModule objects via the django orm.
Data for the other scopes is stored in individual objects that are named for the scope involved and have the field name as a key
If the key isn’t found in the expected table during a read or a delete, then a KeyError will be raised
- delete(key)#
Deletes key from storage.
- get(key)#
Reads the value of the given key from storage.
- has(key)#
Returns whether or not key is present in storage.
- set(key, value)#
Set a single value in the KeyValueStore
- set_many(kv_dict)#
Provide a bulk save mechanism.
- kv_dict: A dictionary of dirty fields that maps
xblock.KvsFieldData._key : value
- class lms.djangoapps.courseware.model_data.DjangoOrmFieldCache#
Bases:
objectBaseclass for Scope-specific field cache objects that are based on single-row-per-field Django ORM objects.
- cache_fields(fields, xblocks, aside_types)#
Load all fields specified by
fieldsfor the suppliedxblocksandaside_typesinto this cache.- Parameters:
fields (list of str) – Field names to cache.
xblocks (list of
XBlock) – XBlocks to cache fields for.aside_types (list of str) – Aside types to cache fields for.
- delete(kvs_key)#
Delete the value specified by kvs_key.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Raises: KeyError if key isn’t found in the cache
- get(kvs_key)#
Return the django model object specified by kvs_key from the cache.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Returns: A django orm object from the cache
- has(kvs_key)#
Return whether the specified kvs_key is set.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Returns: bool
- last_modified(kvs_key)#
Return when the supplied field was changed.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Returns: datetime if there was a modified date, or None otherwise
- set(kvs_key, value)#
Set the specified kvs_key to the field value value.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
value – The field value to store
- set_many(kv_dict)#
Set the specified fields to the supplied values.
- Parameters:
kv_dict (dict) – A dictionary mapping
Keyobjects to values to set.
- class lms.djangoapps.courseware.model_data.FieldDataCache(blocks, course_id, user, asides=None, read_only=False)#
Bases:
objectA cache of django model objects needed to supply the data for a block and its descendants
- add_block_descendents(block, depth=None, block_filter=<function FieldDataCache.<lambda>>)#
Add all descendants of block to this FieldDataCache.
- Parameters:
block – An XBlock
for (depth is the number of levels of descendant blocks to load StudentModules) – the supplied block. If depth is None, load all descendant StudentModules
to (in addition) – the supplied block. If depth is None, load all descendant StudentModules
data (block_filter is a function that accepts a block and return whether the field) – should be cached
- add_blocks_to_cache(blocks)#
Add all blocks to this FieldDataCache.
- classmethod cache_for_block_descendents(course_id, user, block, depth=None, block_filter=<function FieldDataCache.<lambda>>, asides=None, read_only=False)#
course_id: the course in the context of which we want StudentModules. user: the django user for whom to load modules. block: An XBlock depth is the number of levels of descendant blocks to load StudentModules for, in addition to
the supplied block. If depth is None, load all descendant StudentModules
- block_filter is a function that accepts a block and return whether the field data
should be cached
- delete(key)#
Delete the value specified by key.
- Parameters:
key (DjangoKeyValueStore.Key) – The field value to delete
Raises: KeyError if key isn’t found in the cache
- get(key)#
Load the field value specified by key.
- Parameters:
key (DjangoKeyValueStore.Key) – The field value to load
Returns: The found value Raises: KeyError if key isn’t found in the cache
- has(key)#
Return whether the specified key is set.
- Parameters:
key (DjangoKeyValueStore.Key) – The field value to delete
Returns: bool
- last_modified(key)#
Return when the supplied field was changed.
- Parameters:
key (DjangoKeyValueStore.Key) – The field value to delete
Returns: datetime if there was a modified date, or None otherwise
- exception lms.djangoapps.courseware.model_data.InvalidWriteError#
Bases:
ExceptionRaised to indicate that writing to a particular key in the KeyValueStore is disabled
- class lms.djangoapps.courseware.model_data.PreferencesCache(user)#
Bases:
DjangoOrmFieldCacheCache for Scope.preferences xblock field data.
- class lms.djangoapps.courseware.model_data.ScoresClient(course_key, user_id)#
Bases:
objectBasic client interface for retrieving Score information.
Eventually, this should read and write scores, but at the moment it only handles the read side of things.
- class Score(correct, total, created)#
Bases:
tuple- correct#
Alias for field number 0
- created#
Alias for field number 2
- total#
Alias for field number 1
- classmethod create_for_locations(course_id, user_id, scorable_locations)#
Create a ScoresClient with pre-fetched data for the given locations.
- fetch_scores(locations)#
Grab score information.
- get(location)#
Get the score for a given location, if it exists.
If we don’t have a score for that location, return None. Note that as convention, you should be passing in a location with full course run information.
- class lms.djangoapps.courseware.model_data.UserInfoCache(user)#
Bases:
DjangoOrmFieldCacheCache for Scope.user_info xblock field data
- class lms.djangoapps.courseware.model_data.UserStateCache(user, course_id)#
Bases:
objectCache for Scope.user_state xblock field data.
- cache_fields(fields, xblocks, aside_types)#
Load all fields specified by
fieldsfor the suppliedxblocksandaside_typesinto this cache.- Parameters:
fields (list of str) – Field names to cache.
xblocks (list of
XBlock) – XBlocks to cache fields for.aside_types (list of str) – Aside types to cache fields for.
- delete(kvs_key)#
Delete the value specified by kvs_key.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Raises: KeyError if key isn’t found in the cache
- get(kvs_key)#
Return the django model object specified by kvs_key from the cache.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Returns: A django orm object from the cache
- has(kvs_key)#
Return whether the specified kvs_key is set.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
Returns: bool
- last_modified(kvs_key)#
Return when the supplied field was changed.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The key representing the cached field
Returns: datetime if there was a modified date, or None otherwise
- set(kvs_key, value)#
Set the specified kvs_key to the field value value.
- Parameters:
kvs_key (DjangoKeyValueStore.Key) – The field value to delete
value – The field value to store
- set_many(kv_dict)#
Set the specified fields to the supplied values.
- Parameters:
kv_dict (dict) – A dictionary mapping
Keyobjects to values to set.
- class lms.djangoapps.courseware.model_data.UserStateSummaryCache(course_id)#
Bases:
DjangoOrmFieldCacheCache for Scope.user_state_summary xblock field data.
- lms.djangoapps.courseware.model_data.get_score(user_id, usage_key)#
Get the score and max_score for the specified user and xblock usage. Returns None if not found.
- lms.djangoapps.courseware.model_data.set_score(user_id, usage_key, score, max_score)#
Set the score and max_score for the specified user and xblock usage.
lms.djangoapps.courseware.models module#
WE’RE USING MIGRATIONS!
If you make changes to this model, be sure to create an appropriate migration file and check it in at the same time as your model changes. To do that,
Go to the edx-platform dir
./manage.py schemamigration courseware –auto description_of_your_change
Add the migration file created in edx-platform/lms/djangoapps/courseware/migrations/
ASSUMPTIONS: modules have unique IDs, even across different module_types
- class lms.djangoapps.courseware.models.BaseStudentModuleHistory(*args, **kwargs)#
Bases:
ModelAbstract class containing most fields used by any class storing Student Module History
- HISTORY_SAVING_TYPES = {'problem'}#
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- property csm#
Finds the StudentModule object for this history record, even if our data is split across multiple data stores. Django does not handle this correctly with the built-in student_module property.
- static get_history(student_modules)#
Find history objects across multiple backend stores for a given StudentModule
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- max_grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects#
- static save_history_entry(student_module, history_model_cls, request_cache_key)#
When a StudentModule instance is updated, save the changes in the corresponding activity history table
- state#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- version#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.ChunkingManager(*args, **kwargs)#
Bases:
ManagerManagerthat adds an additional methodchunked_filter()to provide the ability to make select queries with specific chunk sizes.- chunked_filter(chunk_field, items, **kwargs)#
Queries model_class with chunk_field set to chunks of size chunk_size, and all other parameters from **kwargs.
This works around a limitation in sqlite3 on the number of parameters that can be put into a single query.
- Parameters:
chunk_field (str) – The name of the field to chunk the query on.
items – The values for of chunk_field to select. This is chunked into
chunk_sizechunks, and passed as the value for thechunk_fieldkeyword argument tofilter(). This implies thatchunk_fieldshould be an__inkey.chunk_size (int) – The size of chunks to pass. Defaults to 500.
- class lms.djangoapps.courseware.models.CourseDynamicUpgradeDeadlineConfiguration(*args, **kwargs)#
Bases:
OptOutDynamicUpgradeDeadlineMixin,ConfigurationModelPer-course run configuration for dynamic upgrade deadlines.
This model controls dynamic upgrade deadlines on a per-course run level, allowing course runs to have different deadlines or opt out of the functionality altogether.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- KEY_FIELDS = ('course_id',)#
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- change_date#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- changed_by#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- changed_by_id#
- course_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- deadline_days#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- enabled#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=True, **kwargs)#
- get_previous_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- opt_out#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.DynamicUpgradeDeadlineConfiguration(*args, **kwargs)#
Bases:
ConfigurationModelDynamic upgrade deadline configuration.
This model controls the behavior of the dynamic upgrade deadline for self-paced courses.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- change_date#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- changed_by#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- changed_by_id#
- deadline_days#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- enabled#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=True, **kwargs)#
- get_previous_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.FinancialAssistanceConfiguration(*args, **kwargs)#
Bases:
ConfigurationModelManages configuration for connecting to Financial Assistance backend service and using its API.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- api_base_url#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- change_date#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- changed_by#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- changed_by_id#
- enabled#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- fa_backend_enabled_courses_percentage#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=True, **kwargs)#
- get_previous_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=False, **kwargs)#
- get_service_user()#
Getter function to get service user for Financial Assistance backend.
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- service_username#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.LastSeenCoursewareTimezone(*args, **kwargs)#
Bases:
ModelThe timezone in the user’s account is frequently not set. This model stores a user’s recent timezone that can be used as a fallback
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- last_seen_courseware_timezone#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>#
- user#
Accessor to the related object on the forward side of a one-to-one relation.
In the example:
class Restaurant(Model): place = OneToOneField(Place, related_name='restaurant')
Restaurant.placeis aForwardOneToOneDescriptorinstance.
- user_id#
- class lms.djangoapps.courseware.models.OfflineComputedGrade(*args, **kwargs)#
Bases:
ModelTable of grades computed offline for a given user and course.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- course_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_updated(*, field=<django.db.models.fields.DateTimeField: updated>, is_next=True, **kwargs)#
- get_previous_by_updated(*, field=<django.db.models.fields.DateTimeField: updated>, is_next=False, **kwargs)#
- gradeset#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>#
- updated#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- user#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- user_id#
- class lms.djangoapps.courseware.models.OfflineComputedGradeLog(*args, **kwargs)#
Bases:
ModelLog of when offline grades are computed. Use this to be able to show instructor when the last computed grades were done.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- course_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- nstudents#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>#
- seconds#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.OptOutDynamicUpgradeDeadlineMixin#
Bases:
objectProvides convenience methods for interpreting the enabled and opt out status.
- opted_in()#
Convenience function that returns True if this config model is both enabled and opt_out is False
- opted_out()#
Convenience function that returns True if this config model is both enabled and opt_out is True
- class lms.djangoapps.courseware.models.OrgDynamicUpgradeDeadlineConfiguration(*args, **kwargs)#
Bases:
OptOutDynamicUpgradeDeadlineMixin,ConfigurationModelPer-org configuration for dynamic upgrade deadlines.
This model controls dynamic upgrade deadlines on a per-org level, allowing organizations to have different deadlines or opt out of the functionality altogether.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- KEY_FIELDS = ('org_id',)#
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- change_date#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- changed_by#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- changed_by_id#
- deadline_days#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- enabled#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=True, **kwargs)#
- get_previous_by_change_date(*, field=<django.db.models.fields.DateTimeField: change_date>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- opt_out#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- org_id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.StudentFieldOverride(*args, **kwargs)#
Bases:
TimeStampedModelHolds the value of a specific field overriden for a student. This is used by the code in the lms.djangoapps.courseware.student_field_overrides module to provide overrides of xblock fields on a per user basis.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- course_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- field#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- location#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>#
- student#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- student_id#
- value#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.StudentModule(*args, **kwargs)#
Bases:
ModelKeeps student state for a particular XBlock usage and particular student.
Called Module since it was originally used for XModule state.
- DONE_TYPES = (('na', 'NOT_APPLICABLE'), ('f', 'FINISHED'), ('i', 'INCOMPLETE'))#
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- classmethod all_submitted_problems_read_only(course_id)#
Return all model instances that correspond to problems that have been submitted for a given course. So module_type=’problem’ and a non-null grade. Use a read replica if one exists for this environment.
- course_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- done#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_done_display(*, field=<django.db.models.fields.CharField: done>)#
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)#
- classmethod get_state_by_params(course_id, module_state_keys, student_id=None)#
Return all model instances that correspond to a course and module keys.
Student ID is optional keyword argument, if provided it narrows down the instances.
- grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- max_grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- module_state_key#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- module_type#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <lms.djangoapps.courseware.models.ChunkingManager object>#
- classmethod save_state(student, course_id, module_state_key, defaults)#
- scoreoverrider_set#
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_forward_many_to_many_manager()defined below.
- state#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- student#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- student_id#
- studentmodulehistory_set#
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_forward_many_to_many_manager()defined below.
- studentmodulehistoryextended_set#
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_forward_many_to_many_manager()defined below.
- class lms.djangoapps.courseware.models.StudentModuleHistory(*args, **kwargs)#
Bases:
BaseStudentModuleHistoryKeeps a complete history of state changes for a given XModule for a given Student. Right now, we restrict this to problems so that the table doesn’t explode in size.
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- max_grade#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- save_history(instance, **kwargs)#
Checks the instance’s module_type, and creates & saves a StudentModuleHistory entry if the module_type is one that we save.
- state#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- student_module#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- student_module_id#
- version#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.XBlockFieldBase(*args, **kwargs)#
Bases:
ModelBase class for all XBlock field storage.
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- field_name#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)#
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects#
- value#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.XModuleStudentInfoField(*args, **kwargs)#
Bases:
XBlockFieldBaseStores data set in the Scope.preferences scope by an xmodule field
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- field_name#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- student#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- student_id#
- value#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.XModuleStudentPrefsField(*args, **kwargs)#
Bases:
XBlockFieldBaseStores data set in the Scope.preferences scope by an xmodule field
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- field_name#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- module_type#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- student#
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- student_id#
- value#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class lms.djangoapps.courseware.models.XModuleUserStateSummaryField(*args, **kwargs)#
Bases:
XBlockFieldBaseStores data set in the Scope.user_state_summary scope by an xblock field
- exception DoesNotExist#
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned#
Bases:
MultipleObjectsReturned
- created#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- field_name#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)#
- get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)#
- get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)#
- get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)#
- id#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- modified#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- usage_id#
DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!
A placeholder class that provides a way to set the attribute on the model.
- value#
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- lms.djangoapps.courseware.models.chunks(items, chunk_size)#
Yields the values from items in chunks of size chunk_size
lms.djangoapps.courseware.permissions module#
Permission definitions for the courseware djangoapp
lms.djangoapps.courseware.plugins module#
Course app config for courseware apps.
- class lms.djangoapps.courseware.plugins.CalculatorCourseApp#
Bases:
CourseAppCourse App config for calculator app.
- app_id: str = 'calculator'#
- description: str = 'Provide an in-course calculator for simple and complex calculations.'#
- documentation_links: Dict = {'learn_more_configuration': 'https://docs.openedx.org/en/latest/educators/how-tos/course_development/exercise_tools/add_calculator.html'}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Get allowed operations for calculator app.
- classmethod is_available(course_key: CourseKey) bool#
Calculator is available for all courses.
- classmethod is_enabled(course_key: CourseKey) bool#
Get calculator enabled status from course overview model.
- name: str = 'Calculator'#
- class lms.djangoapps.courseware.plugins.CustomPagesCourseApp#
Bases:
CourseAppCourse app config for custom pages app.
- app_id: str = 'custom_pages'#
- description: str = 'Provide additional course content and resources with custom pages'#
- documentation_links: Dict = {'learn_more_configuration': 'https://docs.openedx.org/en/latest/educators/how-tos/course_development/manage_custom_page.html'}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Returns the allowed operations for the app.
- classmethod is_available(course_key: CourseKey) bool#
The custom pages app is available for all courses.
- classmethod is_enabled(course_key: CourseKey) bool#
Returns if the custom pages app is enabled. For now this feature is disabled without any manual setup
- static legacy_link(course_key: CourseKey)#
- name: str = 'Custom pages'#
- class lms.djangoapps.courseware.plugins.DatesCourseApp#
Bases:
CourseAppCourse app stub for course dates.
- app_id: str = 'dates'#
- description: str = 'Provide learners a summary of important course dates.'#
- documentation_links: Dict = {'learn_more_configuration': ''}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Returns the allowed operations for the app.
- classmethod is_available(course_key: CourseKey) bool#
Dates app is available when explicitly enabled via settings.
- classmethod is_enabled(course_key: CourseKey) bool#
The dates course status is stored in the course block.
- name: str = 'Dates'#
- class lms.djangoapps.courseware.plugins.ORASettingsApp#
Bases:
CourseAppCourse App config for Flexible Peer Grading ORA app.
- app_id: str = 'ora_settings'#
- description: str = 'Course level settings for Flexible Peer Grading Open Response Assessments.'#
- documentation_links: Dict = {'learn_more_configuration': 'https://docs.openedx.org/en/latest/educators/how-tos/course_development/exercise_tools/Manage_ORA_Assignment.html'}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Get allowed operations for open response app.
- classmethod is_available(course_key: CourseKey) bool#
Open response is available for course with at least one ORA.
- classmethod is_enabled(course_key: CourseKey) bool#
Get open response enabled status from course overview model.
- name: str = 'Flexible Peer Grading for ORAs'#
- class lms.djangoapps.courseware.plugins.ProctoringCourseApp#
Bases:
CourseAppCourse App config for proctoring app.
- app_id: str = 'proctoring'#
- description: str = 'Maintain exam integrity by enabling a proctoring solution for your course'#
- documentation_links: Dict = {'learn_more_configuration': ''}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Get allowed operations for proctoring app.
- classmethod is_available(course_key: CourseKey) bool#
Returns true if the proctoring app is available for all courses.
- classmethod is_enabled(course_key: CourseKey) bool#
Get proctoring enabled status from course overview model.
- name: str = 'Proctoring'#
- class lms.djangoapps.courseware.plugins.ProgressCourseApp#
Bases:
CourseAppCourse app config for progress app.
- app_id: str = 'progress'#
- description: str = 'Keep learners engaged and on track throughout the course.'#
- documentation_links: Dict = {'learn_more_configuration': 'https://docs.openedx.org/en/latest/educators/references/data/progress_page.html'}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Returns the allowed operations for the app.
- classmethod is_available(course_key: CourseKey) bool#
The progress course app is always available.
- classmethod is_enabled(course_key: CourseKey) bool#
The progress course status is stored in the course block.
- name: str = 'Progress'#
- class lms.djangoapps.courseware.plugins.TextbooksCourseApp#
Bases:
CourseAppCourse app config for textbooks app.
- app_id: str = 'textbooks'#
- description: str = 'Create and manage a library of course readings, textbooks, and chapters.'#
- documentation_links: Dict = {'learn_more_configuration': 'https://docs.openedx.org/en/latest/educators/how-tos/course_development/manage_textbooks.html'}#
- classmethod get_allowed_operations(course_key: CourseKey, user: User | None = None) Dict[str, bool]#
Returns the allowed operations for the app.
- classmethod is_available(course_key: CourseKey) bool#
The textbook app can be made available globally using a value in features.
- classmethod is_enabled(course_key: CourseKey) bool#
Returns if the textbook app is globally enabled.
- static legacy_link(course_key: CourseKey)#
- name: str = 'Textbooks'#
lms.djangoapps.courseware.rules module#
django-rules and Bridgekeeper rules for courseware related features
- class lms.djangoapps.courseware.rules.HasAccessRule(action, strict=False)#
Bases:
RuleA rule that calls has_access to determine whether it passes
- check(user, instance=None)#
Check if a user satisfies this rule.
Given a user, return a boolean indicating if that user satisfies this rule for a given instance, or if none is provided, every instance.
- query(user)#
Generate a
Qobject.Note
This method is used internally by
filter(); subclasses will need to override it but you should never need to call it directly.Given a user, return a
Qobject which will filter a queryset down to only instances for which the given user satisfies this rule.Alternatively, return
UNIVERSALif this user satisfies this rule for every possible object, orEMPTYif this user cannot satisfy this rule for any possible object. (These two values are usually only returned in “blanket rules” which depend only on some property of the user, e.g. the built-inis_staff, but these are usually best created with theblanket_ruledecorator.)- Parameters:
user (django.contrib.auth.models.User) – The user to match against.
- Returns:
A query that will filter a queryset to match this rule.
- Return type:
- class lms.djangoapps.courseware.rules.HasRolesRule(*roles)#
Bases:
Rule- check(user, instance=None)#
Check if a user satisfies this rule.
Given a user, return a boolean indicating if that user satisfies this rule for a given instance, or if none is provided, every instance.
- class lms.djangoapps.courseware.rules.HasStaffAccessToContent#
Bases:
RuleCheck whether a user has staff access in a course.
Expects to be used to filter a CourseOverview queryset
- check(user, instance=None)#
Return True if the supplied user has staff-level access to the supplied content.
- query(user)#
Returns a Q object that expects to be used to filter CourseOverview queries.
- class lms.djangoapps.courseware.rules.StaffAccessExperiment(name='Experiment', context=None, raise_on_mismatch=False)#
Bases:
Experiment- compare(control, candidate)#
Compares two
Observationinstances.- Parameters:
control (Observation) – The control block’s
Observationcandidate (Observation) – A candidate block’s
Observation
- Raises:
MismatchException – If
Experiment.raise_on_mismatchis True- Return bool:
match?
- publish(result)#
Publish the results of an experiment. This is called after each experiment run. Exceptions that occur during publishing will be caught, but logged.
By default this is a no-op. See publishing.
- Parameters:
result (Result) – The result of an experiment run
lms.djangoapps.courseware.self_paced_overrides module#
Field overrides for self-paced courses. This allows overriding due dates for each block in the course.
- class lms.djangoapps.courseware.self_paced_overrides.SelfPacedDateOverrideProvider(user, fallback_field_data)#
Bases:
FieldOverrideProviderA concrete implementation of
FieldOverrideProviderwhich allows for due dates to be overridden for self-paced courses.- classmethod enabled_for(block)#
This provider is enabled for self-paced courses only.
- get(block, name, default)#
Look for an override value for the field named name in block. Returns the overridden value or default if no override is found.
lms.djangoapps.courseware.services module#
Courseware services.
- class lms.djangoapps.courseware.services.UserStateService#
Bases:
objectUser state service to make state accessible in runtime.
- get_state_as_dict(username_or_email, block_id)#
Return dict containing user state for a given set of parameters.
- Parameters:
username_or_email – username or email of the user for whom the data is being retrieved
block_id – string/object representation of the block whose user state is required
- Returns:
Returns a dict containing user state, if present, else empty.
lms.djangoapps.courseware.student_field_overrides module#
API related to providing field overrides for individual students. This is used by the individual due dates feature.
- class lms.djangoapps.courseware.student_field_overrides.IndividualStudentOverrideProvider(user, fallback_field_data)#
Bases:
FieldOverrideProviderA concrete implementation of
FieldOverrideProviderwhich allows for overrides to be made on a per user basis.- classmethod enabled_for(course)#
This simple override provider is always enabled
- get(block, name, default)#
Look for an override value for the field named name in block. Returns the overridden value or default if no override is found.
- lms.djangoapps.courseware.student_field_overrides.clear_override_for_user(user, block, name)#
Clears a previously set field override for the user. block and name specify the block and the name of the field on that block to clear. This function is idempotent–if no override is set, nothing action is performed.
- lms.djangoapps.courseware.student_field_overrides.get_override_for_user(user, block, name, default=None)#
Gets the value of the overridden field for the user. block and name specify the block and the name of the field. If the field is not overridden for the given user, returns default.
- lms.djangoapps.courseware.student_field_overrides.override_field_for_user(user, block, name, value)#
Overrides a field for the user. block and name specify the block and the name of the field on that block to override. value is the value to set for the given field.
lms.djangoapps.courseware.tabs module#
This module is essentially a broker to xmodule/tabs.py – it was originally introduced to perform some LMS-specific tab display gymnastics for the Entrance Exams feature
- class lms.djangoapps.courseware.tabs.CoursewareTab(tab_dict)#
Bases:
EnrolledTabThe main courseware view.
- is_default = False#
- classmethod is_enabled(course, user=None)#
Courseware tabs are viewable to everyone, even anonymous users.
- is_movable = False#
- priority = 11#
- title = 'Course'#
- type = 'courseware'#
- view_name = 'courseware'#
- class lms.djangoapps.courseware.tabs.DatesTab(tab_dict)#
Bases:
EnrolledTabA tab representing the relevant dates for a course.
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- is_hideable = True#
- priority = 30#
- title = 'Dates'#
- type = 'dates'#
- view_name = 'dates'#
- class lms.djangoapps.courseware.tabs.EnrolledTab(tab_dict)#
Bases:
CourseTabA base class for any view types that require a user to be enrolled.
- class lms.djangoapps.courseware.tabs.ExternalDiscussionCourseTab(tab_dict=None, link=None)#
Bases:
LinkTabA course tab that links to an external discussion service.
- is_default = False#
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- priority = None#
- title = 'Discussion'#
- type = 'external_discussion'#
- classmethod validate(tab_dict, raise_error=True)#
Validate that the tab_dict for this course tab has the necessary information to render.
- class lms.djangoapps.courseware.tabs.ExternalLinkCourseTab(tab_dict=None, link=None)#
Bases:
LinkTabA course tab containing an external link.
- allow_multiple = True#
- is_default = False#
- priority = 110#
- type = 'external_link'#
- classmethod validate(tab_dict, raise_error=True)#
Validate that the tab_dict for this course tab has the necessary information to render.
- class lms.djangoapps.courseware.tabs.HtmlTextbookTabs(tab_dict)#
Bases:
TextbookTabsBaseA tab representing the collection of all Html textbook tabs.
- classmethod items(course)#
A generator for iterating through all the SingleTextbookTab book objects associated with this collection of textbooks.
- priority = 202#
- type = 'html_textbooks'#
- view_name = 'html_book'#
- class lms.djangoapps.courseware.tabs.LinkTab(tab_dict=None, link=None)#
Bases:
CourseTabAbstract class for tabs that contain external links.
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- link_value = ''#
- to_json()#
Serializes the necessary members of the CourseTab object to a json-serializable representation. This method is overridden by subclasses that have more members to serialize.
- Returns:
a dictionary with keys for the properties of the CourseTab object.
- class lms.djangoapps.courseware.tabs.PDFTextbookTabs(tab_dict)#
Bases:
TextbookTabsBaseA tab representing the collection of all PDF textbook tabs.
- classmethod items(course)#
A generator for iterating through all the SingleTextbookTab book objects associated with this collection of textbooks.
- priority = 201#
- type = 'pdf_textbooks'#
- view_name = 'pdf_book'#
- class lms.djangoapps.courseware.tabs.ProgressTab(tab_dict)#
Bases:
EnrolledTabThe course progress view.
- is_default = False#
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- is_hideable = True#
- priority = 20#
- title = 'Progress'#
- type = 'progress'#
- view_name = 'progress'#
- class lms.djangoapps.courseware.tabs.SingleTextbookTab(name, tab_id, view_name, index)#
Bases:
CourseTabA tab representing a single textbook. It is created temporarily when enumerating all textbooks within a Textbook collection tab. It should not be serialized or persisted.
- is_collection_item = True#
- is_movable = False#
- priority = None#
- to_json()#
Serializes the necessary members of the CourseTab object to a json-serializable representation. This method is overridden by subclasses that have more members to serialize.
- Returns:
a dictionary with keys for the properties of the CourseTab object.
- type = 'single_textbook'#
- class lms.djangoapps.courseware.tabs.SyllabusTab(tab_dict)#
Bases:
EnrolledTabA tab for the course syllabus.
- allow_multiple = True#
- is_default = False#
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- priority = 80#
- title = 'Syllabus'#
- type = 'syllabus'#
- view_name = 'syllabus'#
- class lms.djangoapps.courseware.tabs.TextbookTabs(tab_dict)#
Bases:
TextbookTabsBaseA tab representing the collection of all textbook tabs.
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- classmethod items(course)#
A generator for iterating through all the SingleTextbookTab book objects associated with this collection of textbooks.
- priority = 200#
- type = 'textbooks'#
- view_name = 'book'#
- class lms.djangoapps.courseware.tabs.TextbookTabsBase(tab_dict)#
Bases:
CourseTabAbstract class for textbook collection tabs classes.
- is_collection = True#
- is_default = False#
- classmethod is_enabled(course, user=None)#
Returns true if this course tab is enabled in the course.
- Parameters:
course (CourseBlock) – the course using the feature
user (User) – an optional user interacting with the course (defaults to None)
- classmethod items(course)#
A generator for iterating through all the SingleTextbookTab book objects associated with this collection of textbooks.
- title = 'Textbooks'#
- lms.djangoapps.courseware.tabs.get_course_tab_list(user, course)#
Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
lms.djangoapps.courseware.toggles module#
Toggles for courseware in-course experience.
- lms.djangoapps.courseware.toggles.course_exit_page_is_active(course_key)#
- lms.djangoapps.courseware.toggles.course_is_invitation_only(courselike) bool#
Returns whether the course is invitation only or not.
Return whether the courseware.disable_navigation_sidebar_blocks_caching flag is on.
- lms.djangoapps.courseware.toggles.courseware_mfe_progress_milestones_are_active(course_key)#
- lms.djangoapps.courseware.toggles.courseware_mfe_search_is_enabled(course_key=None)#
Return whether the courseware.mfe_courseware_search flag is on.
- lms.djangoapps.courseware.toggles.streak_celebration_is_active(course_key)#
lms.djangoapps.courseware.transformers module#
Courseware BlockTransformer implementations
- class lms.djangoapps.courseware.transformers.OpenAssessmentDateTransformer#
Bases:
FilteringTransformerMixin,BlockStructureTransformerBlockTransformer to collect all fields related to dates for openassessment problems.
- READ_VERSION = 1#
- WRITE_VERSION = 2#
- classmethod collect(block_structure)#
Collects any information that’s necessary to execute this transformer’s transform method.
- classmethod name()#
Unique identifier for the transformer’s class. This must match the entry point name in the package configuration.
- transform_block_filters(usage_info, block_structure)#
This is an alternative to the standard transform method.
Returns a list of filter functions to be used for filtering out any unwanted blocks in the given block_structure.
In addition to the commonly used methods listed above, the following methods are commonly used by implementations of transform_block_filters:
create_universal_filter create_removal_filter
Note: Transformers that implement this alternative should be independent of all other registered transformers as they may not be applied in the order in which they were listed in the registry.
- Parameters:
usage_info (any negotiated type) – that is passed to the block_structure and forwarded to all requested Transformers in order to apply a usage-specific transform. For example, an instance of usage_info would contain a user object for which the transform should be applied.
block_structure (BlockStructureBlockData) – block structure, with already collected data for the transformer, that is to be transformed in place.
lms.djangoapps.courseware.user_state_client module#
An implementation of XBlockUserStateClient, which stores XBlock Scope.user_state
data in a Django ORM model.
- class lms.djangoapps.courseware.user_state_client.DjangoXBlockUserStateClient(user=None)#
Bases:
XBlockUserStateClientAn interface that uses the Django ORM StudentModule as a backend.
- A note on the format of state storage:
The state for an xblock is stored as a serialized JSON dictionary. The model field that it is stored in can also take on a value of
None. To preserve existing analytic uses, we will preserve the following semantics:A state of
Nonemeans that the user hasn’t ever looked at the xblock. A state of"{}"means that the XBlock has at some point stored state forthe current user, but that that state has been deleted.
Otherwise, the dictionary contains all data stored for the user.
None of these conditions should violate the semantics imposed by XBlockUserStateClient (for instance, once all fields have been deleted from an XBlock for a user, the state will be listed as
Nonebyget_history(), even though the actual stored state in the database will be"{}").
- exception DoesNotExist#
Bases:
DoesNotExistThis error is raised if the caller has requested data that does not exist.
- exception PermissionDenied#
Bases:
PermissionDeniedThis error is raised if the caller is not allowed to access the requested data.
Bases:
ServiceUnavailableThis error is raised if the service backing this client is currently unavailable.
- delete_many(username, block_keys, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Delete the stored XBlock state for a many xblock usages.
- Parameters:
username – The name of the user whose state should be deleted
block_keys (list) – The UsageKey identifying which xblock state to delete.
scope (Scope) – The scope to delete data from
fields – A list of fields to delete. If None, delete all stored fields.
- get_history(username, block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Retrieve history of state changes for a given block for a given student. We don’t guarantee that history for many blocks will be fast.
If the specified block doesn’t exist, raise
DoesNotExist.- Parameters:
username – The name of the user whose history should be retrieved.
block_key – The key identifying which xblock history to retrieve.
scope (Scope) – The scope to load data from.
- Yields:
XBlockUserState entries for each modification to the specified XBlock, from latest to earliest.
- get_many(username, block_keys, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Retrieve the stored XBlock state for the specified XBlock usages.
- Parameters:
username – The name of the user whose state should be retrieved
block_keys ([UsageKey]) – A list of UsageKeys identifying which xblock states to load.
scope (Scope) – The scope to load data from
fields – A list of field values to retrieve. If None, retrieve all stored fields.
- Yields:
XBlockUserState tuples for each specified UsageKey in block_keys. field_state is a dict mapping field names to values.
- iter_all_for_block(block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Return an iterator over the data stored in the block (e.g. a problem block).
You get no ordering guarantees.If you’re using this method, you should be running in an async task.
- Parameters:
block_key – an XBlock’s locator (e.g.
BlockUsageLocator)scope (Scope) – must be Scope.user_state
- Returns:
- an iterator over all data. Each invocation returns the next
XBlockUserState object, which includes the block’s contents.
- an iterator over all data. Each invocation returns the next
- iter_all_for_course(course_key, block_type=None, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Return an iterator over all data stored in a course’s blocks.
You get no ordering guarantees. If you’re using this method, you should be running in an async task.
- Parameters:
course_key – a course locator
scope (Scope) – must be Scope.user_state
- Returns:
- an iterator over all data. Each invocation returns the next
XBlockUserState object, which includes the block’s contents.
- an iterator over all data. Each invocation returns the next
- set_many(username, block_keys_to_state, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Set fields for a particular XBlock.
- Parameters:
username – The name of the user whose state should be retrieved
block_keys_to_state (dict) – A dict mapping UsageKeys to state dicts. Each state dict maps field names to values. These state dicts are overlaid over the stored state. To delete fields, use
delete()ordelete_many().scope (Scope) – The scope to load data from
- class lms.djangoapps.courseware.user_state_client.XBlockUserState(username, block_key, state, updated, scope)#
Bases:
_XBlockUserStateThe current state of a single XBlock.
- Parameters:
username – The username of the user that stored this state.
block_key –
The key identifying the scoped state. Depending on the
BlockScopeofscope, this may take one of several types:USAGE:UsageKeyDEFINITION:DefinitionKeyTYPE:strALL:None
state – A dict mapping field names to the values of those fields for this XBlock.
updated – A
datetime.datetime. We guarantee that the fields that were returned in “state” have not been changed since this time (in UTC).scope – A
xblock.fields.Scopeidentifying which XBlock scope this state is coming from.
- class lms.djangoapps.courseware.user_state_client.XBlockUserStateClient#
Bases:
objectFirst stab at an interface for accessing XBlock User State. This will have use StudentModule as a backing store in the default case.
Scope/Goals:
- Mediate access to all student-specific state stored by XBlocks.
This includes “preferences” and “user_info” (i.e. UserScope.ONE)
This includes XBlock Asides.
This may later include user_state_summary (i.e. UserScope.ALL).
This may include group state in the future.
This may include other key types + UserScope.ONE (e.g. Definition)
- Assume network service semantics.
At some point, this will probably be calling out to an external service. Even if it doesn’t, we want to be able to implement circuit breakers, so that a failure in StudentModule doesn’t bring down the whole site. This also implies that the client is running as a user, and whatever is backing it is smart enough to do authorization checks.
This does not yet cover export-related functionality.
- exception DoesNotExist#
Bases:
ExceptionThis error is raised if the caller has requested data that does not exist.
- exception PermissionDenied#
Bases:
ExceptionThis error is raised if the caller is not allowed to access the requested data.
Bases:
ExceptionThis error is raised if the service backing this client is currently unavailable.
- delete(username, block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Delete the stored XBlock state for a single xblock usage.
- Parameters:
username – The name of the user whose state should be deleted
block_key – The key identifying which xblock state to delete.
scope (Scope) – The scope to delete data from
fields – A list of fields to delete. If None, delete all stored fields.
- abstractmethod delete_many(username, block_keys, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Delete the stored XBlock state for a many xblock usages.
- Parameters:
username – The name of the user whose state should be deleted
block_key – The key identifying which xblock state to delete.
scope (Scope) – The scope to delete data from
fields – A list of fields to delete. If None, delete all stored fields.
- get(username, block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Retrieve the stored XBlock state for a single xblock usage.
- Parameters:
username – The name of the user whose state should be retrieved
block_key – The key identifying which xblock state to load.
scope (Scope) – The scope to load data from
fields – A list of field values to retrieve. If None, retrieve all stored fields.
- Returns:
The current state of the block for the specified username and block_key.
- Return type:
- Raises:
DoesNotExist if no entry is found. –
- get_history(username, block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Retrieve history of state changes for a given block for a given student. We don’t guarantee that history for many blocks will be fast.
If the specified block doesn’t exist, raise
DoesNotExist.- Parameters:
username – The name of the user whose history should be retrieved.
block_key – The key identifying which xblock history to retrieve.
scope (Scope) – The scope to load data from.
- Yields:
XBlockUserState entries for each modification to the specified XBlock, from latest to earliest.
- abstractmethod get_many(username, block_keys, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'), fields=None)#
Retrieve the stored XBlock state for a single xblock usage.
- Parameters:
username – The name of the user whose state should be retrieved
block_keys – A list of keys identifying which xblock states to load.
scope (Scope) – The scope to load data from
fields – A list of field values to retrieve. If None, retrieve all stored fields.
- Yields:
XBlockUserState tuples for each specified key in block_keys. field_state is a dict mapping field names to values.
- iter_all_for_block(block_key, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
You get no ordering guarantees. If you’re using this method, you should be running in an async task.
- iter_all_for_course(course_key, block_type=None, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
You get no ordering guarantees. If you’re using this method, you should be running in an async task.
- set(username, block_key, state, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Set fields for a particular XBlock.
- Parameters:
username – The name of the user whose state should be retrieved
block_key – The key identifying which xblock state to load.
state (dict) – A dictionary mapping field names to values
scope (Scope) – The scope to store data to
- abstractmethod set_many(username, block_keys_to_state, scope=(UserScope.ONE, BlockScope.USAGE, 'user_state'))#
Set fields for a particular XBlock.
- Parameters:
username – The name of the user whose state should be retrieved
block_keys_to_state (dict) – A dict mapping keys to state dicts. Each state dict maps field names to values. These state dicts are overlaid over the stored state. To delete fields, use
delete()ordelete_many().scope (Scope) – The scope to load data from
lms.djangoapps.courseware.utils module#
Utility functions that have to do with the courseware.
- lms.djangoapps.courseware.utils.can_show_verified_upgrade(user, enrollment, course=None)#
Return whether this user can be shown upgrade message.
- Parameters:
user (
AuthUser) – The user from the request.user propertyenrollment (
CourseEnrollment) – The enrollment under consideration. If None, then the enrollment is not considered to be upgradeable.course (
ModulestoreCourse) – Optional passed in modulestore course. If provided, it is expected to correspond to enrollment.course.id. If not provided, the course will be loaded from the modulestore. We use the course to retrieve user partitions when calculating whether the upgrade link will be shown.
- lms.djangoapps.courseware.utils.create_financial_assistance_application(form_data)#
Sends a post request to edx-financial-assistance to create a new application for financial assistance application. The incoming form_data must have data as given in the example below: {
“lms_user_id”: <user_id>, “course_id”: <course_run_id>, “certify_economic_hardship”: <Boolean>, “certify_complete_certificate”: <Boolean>, “certify_honor_code”: <Boolean>,
}
- lms.djangoapps.courseware.utils.get_course_hash_value(course_key)#
Returns a hash value for the given course key. If course key is None, function returns an out of bound value which will never satisfy the fa_backend_enabled_courses_percentage condition
- lms.djangoapps.courseware.utils.get_financial_assistance_application_status(user_id, course_id)#
Given the course_id, sends a get request to edx-financial-assistance to retrieve financial assistance application(s) status for the logged-in user.
- lms.djangoapps.courseware.utils.is_eligible_for_financial_aid(course_id)#
Sends a get request to edx-financial-assistance to retrieve financial assistance eligibility criteria for a course.
Returns either True if course is eligible for financial aid or vice versa. Also returns the reason why the course isn’t eligible. In case of a bad request, returns an error message.
- lms.djangoapps.courseware.utils.is_empty_html(html_content)#
Check if HTML content is effectively empty.
- lms.djangoapps.courseware.utils.is_mode_upsellable(user, enrollment, course=None)#
Return whether the user is enrolled in a mode that can be upselled to another mode, usually audit upselled to verified. The partition code allows this function to more accurately return results for masquerading users.
- Parameters:
user (
AuthUser) – The user from the request.user propertyenrollment (
CourseEnrollment) – The enrollment under consideration.course (
ModulestoreCourse) – Optional passed in modulestore course. If provided, it is expected to correspond to enrollment.course.id. If not provided, the course will be loaded from the modulestore. We use the course to retrieve user partitions when calculating whether the upgrade link will be shown.
- lms.djangoapps.courseware.utils.verified_upgrade_deadline_link(user, course=None, course_id=None)#
Format the correct verified upgrade link for the specified
userin a course.One of
courseorcourse_idmust be supplied. If both are specified,coursewill take priority.- Parameters:
user (
User) – The user to display the link for.course (
CourseOverview) – The course to render a link for.course_id (
CourseKey) – The course_id of the course to render for.
- Returns:
The formatted link that will allow the user to upgrade to verified in this course.