Ochs / staff / admin.py

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 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')
    
    class ProfileCreationForm(auth_forms.UserCreationForm):
        class Meta:
            model = Profile
            fields = ("username",)
    
    change_password_form = auth_forms.AdminPasswordChangeForm
    add_form = ProfileCreationForm
    
    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 request.user.position in [FACULTY, SUPERUSER]:
            return True
        else:
            return False
    has_change_permission = has_add_permission
    has_delete_permission = has_add_permission
    
    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)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.