Source

Ochs / staff / admin.py

Full commit
from django import forms
from django.contrib import admin
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import forms as auth_forms
from django.utils.html import escape
from django.template import RequestContext
from django.utils.translation import ugettext, ugettext_lazy as _
from django.forms.models import modelform_factory
from django.utils.functional import curry

from staff.util import check_role
from staff.models import FACULTY, SUPERUSER
from staff.models import Profile, Position

from ochs_admin import admin_site

class PositionAdmin(admin.ModelAdmin):
    pass
admin_site.site.register(Position, PositionAdmin)

class ProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('position',)
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('position',)
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('last_name',)
    exclude = ('groups', 'user_permissions', 'is_staff', 'is_superuser')

    def queryset(self, request):
        if request.user.is_superuser or check_role(request.user, FACULTY):
            qs = self.model._default_manager.get_query_set()
        else:
            qs = self.model._default_manager.get_query_set().filter(pk=request.user.pk)
        return qs

    class ProfileCreationForm(auth_forms.UserCreationForm):
        class Meta:
            model = Profile
            fields = ("username",)
    
    change_password_form = auth_forms.AdminPasswordChangeForm
    add_form = ProfileCreationForm

    def get_form(self, request, obj=None, **kwargs):
        if self.declared_fieldsets:
            fields = flatten_fieldsets(self.declared_fieldsets)
        else:
            fields = None
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude = (exclude + kwargs.get('exclude', []))
        if not request.user.is_superuser and not check_role(request.user, FACULTY):
            exclude = (exclude + ['position', 'is_active', 'last_login','date_joined',])
        defaults = {
            'form': self.form,
            'fields': fields,
            'exclude': exclude,
            'formfield_callback': curry(self.formfield_for_dbfield, request=request),
        }
        defaults.update(kwargs)
        print defaults
        return modelform_factory(self.model, **defaults)
    
    def __call__(self, request, url):
        if url is None:
            return self.changelist_view(request)
        if url.endswith('password'):
            return self.user_change_password(request, url.split('/')[0])
        return super(UserAdmin, self).__call__(request, url)
    
        def save_model(self, request, obj, form, change):
            obj.is_staff = True
            obj.save()
    
    def has_add_permission(self, request, obj=None):
        if request.user.is_superuser or check_role(request.user, [FACULTY, SUPERUSER]):
            return True
        else:
            return False
    has_delete_permission = has_add_permission
   
    def has_change_permission(self, request, obj=None):
        return True 

    def get_urls(self):
        from django.conf.urls.defaults import patterns
        return patterns('',
            (r'^(\d+)/password/$', self.admin_site.admin_view(self.user_change_password))
        ) + super(ProfileAdmin, self).get_urls()
    
    def add_view(self, request):
        if not self.has_change_permission(request):
            if self.has_add_permission(request) and settings.DEBUG:
                # Raise Http404 in debug mode so that the user gets a helpful
                # error message.
                raise Http404('Your user does not have the "Change user" permission. In order to add users, Django requires that your user account have both the "Add user" and "Change user" permissions set.')
            raise PermissionDenied
        if request.method == 'POST':
            form = self.add_form(request.POST)
            if form.is_valid():
                new_user = form.save()
                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
                self.log_addition(request, new_user)
                if "_addanother" in request.POST:
                    request.user.message_set.create(message=msg)
                    return HttpResponseRedirect(request.path)
                elif '_popup' in request.REQUEST:
                    return self.response_add(request, new_user)
                else:
                    request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
                    return HttpResponseRedirect('../%s/' % new_user.id)
        else:
            form = self.add_form()
        return render_to_response('admin/auth/user/add_form.html', {
            'title': _('Add profile'),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_add_permission': True,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_file_field': False,
            'has_absolute_url': False,
            'auto_populated_fields': (),
            'opts': self.model._meta,
            'save_as': False,
            'username_help_text': self.model._meta.get_field('username').help_text,
            'root_path': self.admin_site.root_path,
            'app_label': self.model._meta.app_label,           
        }, context_instance=RequestContext(request))
    
    def user_change_password(self, request, id):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.model, pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                new_user = form.save()
                msg = ugettext('Password changed successfully.')
                request.user.message_set.create(message=msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)
        return render_to_response('admin/auth/user/change_password.html', {
            'title': _('Change password: %s') % escape(user.username),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
            'root_path': self.admin_site.root_path,
        }, context_instance=RequestContext(request))
    
admin_site.site.register(Profile, ProfileAdmin)