<commit_before>from datetime import datetime

from django.contrib import admin, messages
from django import forms
from django.forms import ModelForm
from django.contrib.auth import admin as auth_admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin, FlatpageForm
from django.utils.safestring import mark_safe
from django.http import Http404
from django.conf.urls import url
from django.shortcuts import render, redirect

from codemirror import CodeMirrorTextarea
from suit.admin import SortableModelAdmin

from .forms import UserChangeForm, UserCreationForm, UserLimitedChangeForm, AddOrganizerForm
from .filters import OpenRegistrationFilter
from .models import (
    Coach, Event, User, EventPage, EventPageContent, EventPageMenu, Postmortem,
    Sponsor, Story
)


class EventAdmin(admin.ModelAdmin):
    list_display = ('name', 'organizers', 'email', 'date', 'city', 'country',
                    'is_on_homepage', 'is_past_event', 'has_stats')
    list_filter = (OpenRegistrationFilter,)
    search_fields = ('city', 'country', 'name')
    filter_horizontal = ['team']

    def get_queryset(self, request):
        qs = super(EventAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(team=request.user)

    def is_past_event(self, obj):
        return not obj.is_upcoming()
    is_past_event.boolean = True

    def has_stats(self, obj):
        return Postmortem.objects.filter(event=obj).exists()
    has_stats.boolean = True

    def get_readonly_fields(self, request, obj=None):
        if obj and not request.user.is_superuser:
            return ('email', 'team', 'is_deleted', 'is_on_homepage')
        return self.readonly_fields

    def get_urls(self):
        urls = super(EventAdmin, self).get_urls()
        my_urls = [
            url(r'manage_organizers/$',
                self.admin_site.admin_view(self.view_manage_organizers)),
            url(r'add_organizers/$',
                self.admin_site.admin_view(self.view_add_organizers)),
        ]
        return my_urls + urls

    def _get_future_events_for_user(self, request):
        """
        Retrieves a list of future events, ordered by name
        """
        return self.get_queryset(request) \
            .filter(date__gte=datetime.now() \
            .strftime("%Y-%m-%d")).order_by('name')

    def _get_event_from_get(self, request, all_events):
        """
        Retrieves a particular event from request.GET['event_id'], or
        returns the first one from all events available to the user.
        """
        if 'event_id' in request.GET:
            try:
                return all_events.get(id=request.GET['event_id'])
            except Event.DoesNotExist:
                pass
        else:
            return all_events.first()

    def view_manage_organizers(self, request):
        """
        Custom admin view that allows user to remove organizers from an event
        """
        all_events = self._get_future_events_for_user(request)
        event = self._get_event_from_get(request, all_events)

        if 'remove' in request.GET:
            user = User.objects.get(id=request.GET['remove'])
            event.team.remove(user)
            event.save()
            messages.success(request, 'Organizer {} has been removed'.format(user.get_full_name()))
            return redirect('/admin/core/event/manage_organizers/?event_id={}'.format(event.id))

        return render(request, 'admin/core/event/view_manage_organizers.html', {
            'all_events': all_events,
            'event': event,
        })

    def view_add_organizers(self, request):
        """
        Custom admin view that allows user to add new organizer to an event
        """
        all_events = self._get_future_events_for_user(request)
        event = self._get_event_from_get(request, all_events)

        if request.method == 'POST':
            form = AddOrganizerForm(all_events, request.POST)
            if form.is_valid():
                user = form.save()
                messages.success(request,
                    '{} has been added to your event, yay!'.format(user.get_full_name()))
                return redirect('/admin/core/event/manage_organizers/?event_id={}'.format(event.id))
        else:
            form = AddOrganizerForm(all_events)

        return render(request, 'admin/core/event/view_add_organizers.html', {<commit_msg>Make sure user cannot remove anyone from an event they don't have access too<commit_after>from datetime import datetime

from django.contrib import admin, messages
from django import forms
from django.forms import ModelForm
from django.contrib.auth import admin as auth_admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin, FlatpageForm
from django.utils.safestring import mark_safe
from django.http import Http404
from django.conf.urls import url
from django.shortcuts import render, redirect

from codemirror import CodeMirrorTextarea
from suit.admin import SortableModelAdmin

from .forms import UserChangeForm, UserCreationForm, UserLimitedChangeForm, AddOrganizerForm
from .filters import OpenRegistrationFilter
from .models import (
    Coach, Event, User, EventPage, EventPageContent, EventPageMenu, Postmortem,
    Sponsor, Story
)


class EventAdmin(admin.ModelAdmin):
    list_display = ('name', 'organizers', 'email', 'date', 'city', 'country',
                    'is_on_homepage', 'is_past_event', 'has_stats')
    list_filter = (OpenRegistrationFilter,)
    search_fields = ('city', 'country', 'name')
    filter_horizontal = ['team']

    def get_queryset(self, request):
        qs = super(EventAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(team=request.user)

    def is_past_event(self, obj):
        return not obj.is_upcoming()
    is_past_event.boolean = True

    def has_stats(self, obj):
        return Postmortem.objects.filter(event=obj).exists()
    has_stats.boolean = True

    def get_readonly_fields(self, request, obj=None):
        if obj and not request.user.is_superuser:
            return ('email', 'team', 'is_deleted', 'is_on_homepage')
        return self.readonly_fields

    def get_urls(self):
        urls = super(EventAdmin, self).get_urls()
        my_urls = [
            url(r'manage_organizers/$',
                self.admin_site.admin_view(self.view_manage_organizers)),
            url(r'add_organizers/$',
                self.admin_site.admin_view(self.view_add_organizers)),
        ]
        return my_urls + urls

    def _get_future_events_for_user(self, request):
        """
        Retrieves a list of future events, ordered by name.
        It's based on get_queryset, so superuser see all events, while 
        is_staff users see events they're assigned to only.
        """
        return self.get_queryset(request) \
            .filter(date__gte=datetime.now() \
            .strftime("%Y-%m-%d")).order_by('name')

    def _get_event_from_get(self, request, all_events):
        """
        Retrieves a particular event from request.GET['event_id'], or
        returns the first one from all events available to the user.
        """
        if 'event_id' in request.GET:
            try:
                return all_events.get(id=request.GET['event_id'])
            except Event.DoesNotExist:
                pass
        else:
            return all_events.first()

    def view_manage_organizers(self, request):
        """
        Custom admin view that allows user to remove organizers from an event
        """
        all_events = self._get_future_events_for_user(request)
        event = self._get_event_from_get(request, all_events)

        if 'remove' in request.GET and event in all_events:
            user = User.objects.get(id=request.GET['remove'])
            event.team.remove(user)
            event.save()
            messages.success(request, 'Organizer {} has been removed'.format(user.get_full_name()))
            return redirect('/admin/core/event/manage_organizers/?event_id={}'.format(event.id))

        return render(request, 'admin/core/event/view_manage_organizers.html', {
            'all_events': all_events,
            'event': event,
        })

    def view_add_organizers(self, request):
        """
        Custom admin view that allows user to add new organizer to an event
        """
        all_events = self._get_future_events_for_user(request)
        event = self._get_event_from_get(request, all_events)

        if request.method == 'POST':
            form = AddOrganizerForm(all_events, request.POST)
            if form.is_valid():
                user = form.save()
                messages.success(request,
                    '{} has been added to your event, yay!'.format(user.get_full_name()))
                return redirect('/admin/core/event/manage_organizers/?event_id={}'.format(event.id))
        else:
            form = AddOrganizerForm(all_events)

        return render(request, 'admin/core/event/view_add_organizers.html', {
{'fraction_non_alphanumeric': 0.09888791975577846, 'fraction_numerical': 0.0006541648495420846, 'mean_word_length': 2.7425540595675235, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6045501', 'n_tokens_mistral': 2667, 'n_tokens_neox': 2574, 'n_words': 628}