admin.py 6.9 KB
Newer Older
1
""" Django admin pages for student app """
2
from config_models.admin import ConfigurationModelAdmin
3
from django import forms
4
from django.contrib import admin
5
from django.contrib.admin.sites import NotRegistered
Clinton Blackburn committed
6 7 8
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import ugettext_lazy as _
9 10
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
11

12
from student.models import (
13 14 15 16 17 18 19 20 21 22 23
    CourseAccessRole,
    CourseEnrollment,
    CourseEnrollmentAllowed,
    DashboardConfiguration,
    LinkedInAddToProfileConfiguration,
    PendingNameChange,
    Registration,
    RegistrationCookieConfiguration,
    UserAttribute,
    UserProfile,
    UserTestGroup
24
)
25
from student.roles import REGISTERED_ACCESS_ROLES
26
from xmodule.modulestore.django import modulestore
27

Clinton Blackburn committed
28 29
User = get_user_model()  # pylint:disable=invalid-name

30 31 32

class CourseAccessRoleForm(forms.ModelForm):
    """Form for adding new Course Access Roles view the Django Admin Panel."""
33

34
    class Meta(object):
35
        model = CourseAccessRole
36
        fields = '__all__'
37

38
    email = forms.EmailField(required=True)
39 40 41
    COURSE_ACCESS_ROLES = [(role_name, role_name) for role_name in REGISTERED_ACCESS_ROLES.keys()]
    role = forms.ChoiceField(choices=COURSE_ACCESS_ROLES)

42 43 44 45 46 47 48 49 50 51 52
    def clean_course_id(self):
        """
        Checking course-id format and course exists in module store.
        This field can be null.
        """
        if self.cleaned_data['course_id']:
            course_id = self.cleaned_data['course_id']

            try:
                course_key = CourseKey.from_string(course_id)
            except InvalidKeyError:
53
                raise forms.ValidationError(u"Invalid CourseID. Please check the format and re-try.")
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

            if not modulestore().has_course(course_key):
                raise forms.ValidationError(u"Cannot find course with id {} in the modulestore".format(course_id))

            return course_key

        return None

    def clean_org(self):
        """If org and course-id exists then Check organization name
        against the given course.
        """
        if self.cleaned_data.get('course_id') and self.cleaned_data['org']:
            org = self.cleaned_data['org']
            org_name = self.cleaned_data.get('course_id').org
            if org.lower() != org_name.lower():
                raise forms.ValidationError(
                    u"Org name {} is not valid. Valid name is {}.".format(
                        org, org_name
                    )
                )

        return self.cleaned_data['org']

    def clean_email(self):
        """
        Checking user object against given email id.
        """
        email = self.cleaned_data['email']
        try:
            user = User.objects.get(email=email)
        except Exception:
            raise forms.ValidationError(
87
                u"Email does not exist. Could not find {email}. Please re-enter email address".format(
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
                    email=email
                )
            )

        return user

    def clean(self):
        """
        Checking the course already exists in db.
        """
        cleaned_data = super(CourseAccessRoleForm, self).clean()
        if not self.errors:
            if CourseAccessRole.objects.filter(
                    user=cleaned_data.get("email"),
                    org=cleaned_data.get("org"),
                    course_id=cleaned_data.get("course_id"),
                    role=cleaned_data.get("role")
            ).exists():
                raise forms.ValidationError("Duplicate Record.")

        return cleaned_data

110 111 112 113 114
    def __init__(self, *args, **kwargs):
        super(CourseAccessRoleForm, self).__init__(*args, **kwargs)
        if self.instance.user_id:
            self.fields['email'].initial = self.instance.user.email

115

116
@admin.register(CourseAccessRole)
117 118 119 120
class CourseAccessRoleAdmin(admin.ModelAdmin):
    """Admin panel for the Course Access Role. """
    form = CourseAccessRoleForm
    raw_id_fields = ("user",)
121 122 123 124 125 126 127 128
    exclude = ("user",)

    fieldsets = (
        (None, {
            'fields': ('email', 'course_id', 'org', 'role',)
        }),
    )

129
    list_display = (
130
        'id', 'user', 'org', 'course_id', 'role',
131
    )
132 133 134 135 136 137 138
    search_fields = (
        'id', 'user__username', 'user__email', 'org', 'course_id', 'role',
    )

    def save_model(self, request, obj, form, change):
        obj.user = form.cleaned_data['email']
        super(CourseAccessRoleAdmin, self).save_model(request, obj, form, change)
139

140

141
@admin.register(LinkedInAddToProfileConfiguration)
142 143 144
class LinkedInAddToProfileConfigurationAdmin(admin.ModelAdmin):
    """Admin interface for the LinkedIn Add to Profile configuration. """

145
    class Meta(object):
146 147 148 149 150 151
        model = LinkedInAddToProfileConfiguration

    # Exclude deprecated fields
    exclude = ('dashboard_tracking_code',)


152
@admin.register(CourseEnrollment)
153 154 155 156
class CourseEnrollmentAdmin(admin.ModelAdmin):
    """ Admin interface for the CourseEnrollment model. """
    list_display = ('id', 'course_id', 'mode', 'user', 'is_active',)
    list_filter = ('mode', 'is_active',)
Clinton Blackburn committed
157
    raw_id_fields = ('user',)
158
    search_fields = ('course__id', 'mode', 'user__username',)
159

Clinton Blackburn committed
160 161 162
    def queryset(self, request):
        return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user')

163
    class Meta(object):
164 165 166
        model = CourseEnrollment


Clinton Blackburn committed
167 168 169 170 171
class UserProfileInline(admin.StackedInline):
    """ Inline admin interface for UserProfile model. """
    model = UserProfile
    can_delete = False
    verbose_name_plural = _('User profile')
172 173


Clinton Blackburn committed
174 175 176
class UserAdmin(BaseUserAdmin):
    """ Admin interface for the User model. """
    inlines = (UserProfileInline,)
177

178 179 180 181 182 183 184 185 186
    def get_readonly_fields(self, *args, **kwargs):
        """
        Allows editing the users while skipping the username check, so we can have Unicode username with no problems.
        The username is marked read-only regardless of `ENABLE_UNICODE_USERNAME`, to simplify the bokchoy tests.
        """

        django_readonly = super(UserAdmin, self).get_readonly_fields(*args, **kwargs)
        return django_readonly + ('username',)

187

188
@admin.register(UserAttribute)
189 190 191 192 193 194
class UserAttributeAdmin(admin.ModelAdmin):
    """ Admin interface for the UserAttribute model. """
    list_display = ('user', 'name', 'value',)
    list_filter = ('name',)
    raw_id_fields = ('user',)
    search_fields = ('name', 'value', 'user__username',)
195

196 197
    class Meta(object):
        model = UserAttribute
198

199

200 201 202
admin.site.register(UserTestGroup)
admin.site.register(CourseEnrollmentAllowed)
admin.site.register(Registration)
203
admin.site.register(PendingNameChange)
204
admin.site.register(DashboardConfiguration, ConfigurationModelAdmin)
205
admin.site.register(RegistrationCookieConfiguration, ConfigurationModelAdmin)
206

207

208
# We must first un-register the User model since it may also be registered by the auth app.
209 210 211 212 213
try:
    admin.site.unregister(User)
except NotRegistered:
    pass

Clinton Blackburn committed
214
admin.site.register(User, UserAdmin)