Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: upgrading simple api to drf compatible ( 17th ) #35394

Merged
merged 8 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 47 additions & 25 deletions lms/djangoapps/instructor/views/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
from lms.djangoapps.instructor_task.data import InstructorTaskTypes
from lms.djangoapps.instructor_task.models import ReportStore
from lms.djangoapps.instructor.views.serializer import (
AccessSerializer, RoleNameSerializer, ShowStudentExtensionSerializer, UserSerializer
AccessSerializer, RoleNameSerializer, ShowStudentExtensionSerializer, UserSerializer, BlockDueDateSerializer
)
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.course_groups.cohorts import add_user_to_cohort, is_course_cohorted
Expand Down Expand Up @@ -2933,37 +2933,59 @@ def change_due_date(request, course_id):
due_date.strftime('%Y-%m-%d %H:%M')))


@handle_dashboard_error
@require_POST
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_course_permission(permissions.GIVE_STUDENT_EXTENSION)
@require_post_params('student', 'url')
def reset_due_date(request, course_id):
@method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True), name='dispatch')
class ResetDueDate(APIView):
"""
Rescinds a due date extension for a student on a particular unit.
"""
course = get_course_by_id(CourseKey.from_string(course_id))
student = require_student_from_identifier(request.POST.get('student'))
unit = find_unit(course, request.POST.get('url'))
reason = strip_tags(request.POST.get('reason', ''))
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.GIVE_STUDENT_EXTENSION
serializer_class = BlockDueDateSerializer

@method_decorator(ensure_csrf_cookie)
def post(self, request, course_id):
"""
reset a due date extension to a student for a particular unit.
params:
url (str): The URL related to the block that needs the due date update.
student (str): The email or username of the student whose access is being modified.
reason (str): Optional param.
"""
serializer_data = self.serializer_class(data=request.data, context={'make_due_datetime': True})
if not serializer_data.is_valid():
return HttpResponseBadRequest(reason=serializer_data.errors)

version = getattr(course, 'course_version', None)
student = serializer_data.validated_data.get('student')
if not student:
response_payload = {
'error': f'Could not find student matching identifier: {request.data.get("student")}'
}
return JsonResponse(response_payload)

original_due_date = get_date_for_block(course_id, unit.location, published_version=version)
course = get_course_by_id(CourseKey.from_string(course_id))
unit = find_unit(course, serializer_data.validated_data.get('url'))
reason = strip_tags(serializer_data.validated_data.get('reason', ''))

set_due_date_extension(course, unit, student, None, request.user, reason=reason)
if not original_due_date:
# It's possible the normal due date was deleted after an extension was granted:
return JsonResponse(
_("Successfully removed invalid due date extension (unit has no due date).")
)
version = getattr(course, 'course_version', None)

original_due_date_str = original_due_date.strftime('%Y-%m-%d %H:%M')
return JsonResponse(_(
'Successfully reset due date for student {0} for {1} '
'to {2}').format(student.profile.name, _display_unit(unit),
original_due_date_str))
original_due_date = get_date_for_block(course_id, unit.location, published_version=version)

try:
set_due_date_extension(course, unit, student, None, request.user, reason=reason)
if not original_due_date:
# It's possible the normal due date was deleted after an extension was granted:
return JsonResponse(
_("Successfully removed invalid due date extension (unit has no due date).")
)

original_due_date_str = original_due_date.strftime('%Y-%m-%d %H:%M')
return JsonResponse(_(
'Successfully reset due date for student {0} for {1} '
'to {2}').format(student.profile.name, _display_unit(unit),
original_due_date_str))

except Exception as error: # pylint: disable=broad-except
return JsonResponse({'error': str(error)}, status=400)


@handle_dashboard_error
Expand Down
2 changes: 1 addition & 1 deletion lms/djangoapps/instructor/views/api_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
path('update_forum_role_membership', api.update_forum_role_membership, name='update_forum_role_membership'),
path('send_email', api.send_email, name='send_email'),
path('change_due_date', api.change_due_date, name='change_due_date'),
path('reset_due_date', api.reset_due_date, name='reset_due_date'),
path('reset_due_date', api.ResetDueDate.as_view(), name='reset_due_date'),
path('show_unit_extensions', api.show_unit_extensions, name='show_unit_extensions'),
path('show_student_extensions', api.ShowStudentExtensions.as_view(), name='show_student_extensions'),

Expand Down
36 changes: 36 additions & 0 deletions lms/djangoapps/instructor/views/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,39 @@ def validate_student(self, value):
return None

return user


class BlockDueDateSerializer(serializers.Serializer):
"""
Serializer for handling block due date updates for a specific student.
Fields:
url (str): The URL related to the block that needs the due date update.
due_datetime (str): The new due date and time for the block.
student (str): The email or username of the student whose access is being modified.
reason (str): Reason why updating this.
"""
url = serializers.CharField()
due_datetime = serializers.CharField()
student = serializers.CharField(
max_length=255,
help_text="Email or username of user to change access"
)
reason = serializers.CharField(required=False)

def validate_student(self, value):
"""
Validate that the student corresponds to an existing user.
"""
try:
user = get_student_from_identifier(value)
except User.DoesNotExist:
return None

return user

def __init__(self, *args, **kwargs):
# Get context to check if `due_datetime` should be optional
make_due_datetime = kwargs.get('context', {}).get('make_due_datetime', False)
super().__init__(*args, **kwargs)
if make_due_datetime:
self.fields['due_datetime'].required = False
Loading