Example #1
0
def manage(request):
    """Return a listing of user accounts along with some administrative data (which users are locked out)."""
    log_page_view(request, 'Manage Users')
    undergrads = UserProfile.objects.filter(status='U')
    alumni = UserProfile.objects.filter(status='A')
    if 'sort' in request.GET:
        sort = _get_sort_field(request.GET.get('sort'),
                               request.GET.get('order', 'asc'))
        undergrads = undergrads.order_by(sort)
        alumni = alumni.order_by(sort)
    locked_out_undergrads = [
        profile for profile in undergrads
        if profile.has_bit(STATUS_BITS['LOCKED_OUT'])
    ]
    locked_out_alumni = [
        profile for profile in alumni
        if profile.has_bit(STATUS_BITS['LOCKED_OUT'])
    ]
    directory = (request.GET.get('view', 'admin') == 'directory')
    context = {
        'undergrads': undergrads,
        'alumni': alumni,
        'locked_out_undergrads': locked_out_undergrads,
        'locked_out_alumni': locked_out_alumni,
        'directory': directory
    }
    return render(request,
                  'brothers/manage.html',
                  context,
                  context_instance=RequestContext(request))
Example #2
0
def add_potential(request, name=None):
    """Render and process a form for users to create records of new potential members.

    Optional parameters:
        - name  =>  the unique name (abbreviation) of the rush with which to associate the potential: defaults to none

    """
    log_page_view(request, 'Add Potential')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = PotentialForm(request.POST)
        if form.is_valid():
            potential = form.save(commit=False)
            if rush is not None:
                potential.rush = rush
                rush.updated = datetime.now()
                rush.save()
            potential.save()
            redirect = reverse(
                'all_potentials') if rush is None else rush.get_absolute_url()
            return HttpResponseRedirect(redirect)
    else:
        form = PotentialForm() if rush is None else PotentialForm(
            initial={'rush': rush})
    return render(request,
                  'rush/add_potential.html', {
                      'form': form,
                      'rush': rush,
                      'pledge': False
                  },
                  context_instance=RequestContext(request))
Example #3
0
def add_forum(request):
    """Render and process a form to create a new forum."""
    log_page_view(request, 'Add Forum')
    if request.method == 'POST':
        form = ForumForm(request.POST)
        if form.is_valid():
            forum = form.save(commit=False)
            forum.slug = slugify(forum.name)
            try:
                forum.save()
            except IntegrityError:
                form._errors['name'] = form.error_class(
                    ['That name is too similar to an existing forum name.'])
            else:
                for mod in form.cleaned_data.get('moderators'):
                    forum.moderators.add(mod)
                forum.save()
                log.info('%s (%s) added new forum \'%s\'',
                         request.user.username, request.user.get_full_name(),
                         forum.name)
                return HttpResponseRedirect(reverse('forums'))
    else:
        form = ForumForm()
    return render(request,
                  'forums/add_forum.html', {
                      'form': form,
                      'create': True
                  },
                  context_instance=RequestContext(request))
Example #4
0
def edit_post(request, id):
    """Render and process a form to modify an existing post.

    Required arguments:
        - id    =>  the unique ID of the post to edit (as an integer)

    If 'delete=true' appears in the request's query string, the post will be marked as deleted (i.e., post.deleted will
    be set to True), but the post instance will not actually deleted from the database.

    """
    log_page_view(request, 'Edit Post')
    post = get_object_or_404(Post, id=id)
    profile = request.user.get_profile()
    if post.user != profile and profile not in post.thread.forum.moderators.all() and not profile.is_admin():
        return HttpResponseRedirect(reverse('forbidden'))
    if request.method == 'POST':
        post.body = _bb_code_unescape(post.body)
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.body = _bb_code_escape(post.body)
            post.updated_by = profile
            post.save()
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            post.deleted = True
            post.updated_by = profile
            post.save()
            return HttpResponseRedirect(post.thread.get_absolute_url())
        post.body = _bb_code_unescape(post.body)
        form = PostForm(instance=post)
    return render(request, 'forums/add_post.html',
                  {'form': form, 'forum': post.thread.forum, 'thread': post.thread, 'quote': post.quote, 'create': False, 'post': post},
                  context_instance=RequestContext(request))
Example #5
0
def add_thread(request, slug):
    """Render and process a form to create a new thread.

    Required arguments:
        - slug  =>  the slug of the forum to which the new thread should belong (as a string)

    """
    log_page_view(request, 'Add Thread')
    forum = get_object_or_404(Forum, slug=slug)
    if request.method == 'POST':
        form = ThreadForm(request.POST)
        if form.is_valid():
            profile = request.user.get_profile()
            thread = form.save(commit=False)
            thread.forum = forum
            thread.owner = profile
            thread.slug = slugify(thread.title)
            thread.save()
            thread.subscribers.add(profile)
            thread.save()
            body = _bb_code_escape(form.cleaned_data.get('post'))
            post = Post.objects.create(thread=thread, user=profile, updated_by=profile, number=1, deleted=False, body=body)
            post.save()     # create and save the first post belonging to the new thread
            return HttpResponseRedirect(thread.get_absolute_url())
    else:
        form = ThreadForm()
    return render(request, 'forums/add_thread.html', {'form': form, 'forum': forum, 'create': True},
                  context_instance=RequestContext(request))
Example #6
0
def update_potentials(request, name=None):
    """Process a request to modify several potential members simultaneously.

    Optional parameters:
        - name  =>  the unique name of the rush with which the potentials are associated (as a string): defaults to none

    """
    log_page_view(request, 'Update Potentials')
    if request.method != 'POST':
        return HttpResponseRedirect(reverse('forbidden'))
    action = request.POST.get('action', '')
    if action in ['hide', 'pledge', 'delete']:
        potentials = Potential.objects.filter(id__in=[
            int(potential) for potential in request.POST.getlist('potential')
        ])
        count = potentials.count()
        if action == 'hide':
            potentials.update(hidden=True)
            log.info('%s (%s) marked %d potentials as hidden',
                     request.user.username, request.user.get_full_name(),
                     count)
        elif action == 'pledge':
            potentials.update(pledged=True)
            log.info('%s (%s) marked %d potentials as pledges',
                     request.user.username, request.user.get_full_name(),
                     count)
        else:  # action == 'delete'
            potentials.delete()
            log.info('%s (%s) deleted %d potentials', request.user.username,
                     request.user.get_full_name(), count)
    rush = _get_rush_or_404(name)
    redirect = reverse('all_potentials') if rush is None else reverse(
        'potentials', kwargs={'name': name})
    return HttpResponseRedirect(redirect)
Example #7
0
def edit_announcement(request, id):
    """Render and process a form to modify an existing announcement.

    Required parameters:
        - id    =>  the unique ID of the announcement to edit (as an integer)

    If 'delete=true' appears in the request's query string, the announcement will be deleted.

    """
    log_page_view(request, "Edit Announcement")
    announcement = get_object_or_404(Announcement, id=id)
    profile = request.user.get_profile()
    if announcement.user != request.user and not profile.is_admin():
        return HttpResponseRedirect(reverse("forbidden"))  # only admins may edit other people's announcements
    if request.method == "POST":
        form = AnnouncementForm(request.POST, instance=announcement)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("announcements"))
    else:
        if "delete" in request.GET and request.GET["delete"] == "true":
            text = announcement.text
            announcement.delete()
            log.info("%s (%s) deleted announcement '%s'", request.user.username, request.user.get_full_name(), text)
            return HttpResponseRedirect(reverse("announcements"))
        form = AnnouncementForm(instance=announcement)
    return render(
        request,
        "chapter/edit_announcement.html",
        {"form": form, "id": announcement.id},
        context_instance=RequestContext(request),
    )
Example #8
0
def edit_group_members(request, id):
    """Render and process a form to modify the members of a user group.

    Required parameters:
        - id  =>  the unique ID of the group to edit (as an integer)

    """
    log_page_view(request, 'Edit Group Members')
    group = get_object_or_404(Group, id=id)
    if request.method == 'POST':
        user_ids = []
        for name, value in request.POST.items():
            if name.find('user_') > -1:
                user_ids.append(int(value))
        group.user_set = User.objects.filter(id__in=user_ids)
        group.save()
        del request.session['group_perms']  # clear existing group permissions in case they just changed
        log.info('%s (%s) edited members of group \'%s\'', request.user.username, request.user.get_full_name(), group.name)
        return HttpResponseRedirect(reverse('view_group', kwargs={'id': group.id}))
    else:
        users = User.objects.exclude(is_superuser=True) # only one superuser (root) should exist, so exclude that user
        group_members = group.user_set.all()
        choices = []
        initial = []
        for user in users:
            choices.append([user.id, '%s ... %d' % (user.get_full_name(), user.get_profile().badge)])
            if user in group_members:
                initial.append(user.id)
    return render(request, 'brothers/edit_group_members.html',
                  {'group': group, 'choices': choices, 'initial': initial},
                  context_instance=RequestContext(request))
Example #9
0
def edit_announcement(request, id):
    """Render and process a form to modify an existing announcement.

    Required parameters:
        - id    =>  the unique ID of the announcement to edit (as an integer)

    If 'delete=true' appears in the request's query string, the announcement will be deleted.

    """
    log_page_view(request, 'Edit Announcement')
    announcement = get_object_or_404(Announcement, id=id)
    profile = request.user.get_profile()
    if announcement.user != request.user and not profile.is_admin():
        return HttpResponseRedirect(reverse(
            'forbidden'))  # only admins may edit other people's announcements
    if request.method == 'POST':
        form = AnnouncementForm(request.POST, instance=announcement)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('announcements'))
    else:
        if 'delete' in request.GET and request.GET['delete'] == 'true':
            text = announcement.text
            announcement.delete()
            log.info('%s (%s) deleted announcement \'%s\'',
                     request.user.username, request.user.get_full_name(), text)
            return HttpResponseRedirect(reverse('announcements'))
        form = AnnouncementForm(instance=announcement)
    return render(request,
                  'chapter/edit_announcement.html', {
                      'form': form,
                      'id': announcement.id
                  },
                  context_instance=RequestContext(request))
Example #10
0
def announcements(request):
    """Render a listing of announcements posted by members of the chapter."""

    log_page_view(request, "Announcement List")
    private = False
    if request.user.is_authenticated():
        if "bros_only" in request.GET and request.GET["bros_only"] == "true":
            objects = Announcement.objects.filter(public=False)
            private = True
        else:
            objects = Announcement.objects.all()
        template = "chapter/announcements_bros_only.html"
    else:
        objects = Announcement.objects.filter(public=True)
        template = "chapter/announcements.html"

    paginator = Paginator(objects, settings.ANNOUNCEMENTS_PER_PAGE)
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1  # if 'page' parameter is not an integer, default to page 1
    try:
        announcements = paginator.page(page)
    except (EmptyPage, InvalidPage):
        announcements = paginator.page(paginator.num_pages)

    return render(
        request,
        template,
        {"announcements": announcements, "private": private},
        context_instance=RequestContext(request),
    )
Example #11
0
def view_forum(request, slug):
    """Render a listing of threads in a forum, handling pagination if there are many such threads.

    Required arguments:
        - slug  =>  the slug of the forum to view (as a string)

    """
    log_page_view(request, 'View Forum')
    forum = get_object_or_404(Forum, slug=slug)
    is_mod = (request.user.get_profile() in forum.moderators.all())
    objects = Thread.objects.filter(forum=forum).order_by('-updated')
    paginator = Paginator(objects, settings.POSTS_PER_PAGE)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1  # if 'page' parameter is not an integer, default to page 1
    try:
        threads = paginator.page(page)
    except (EmptyPage, InvalidPage):
        threads = paginator.page(paginator.num_pages)
    return render(request,
                  'forums/view_forum.html', {
                      'threads': threads,
                      'forum': forum,
                      'is_mod': is_mod
                  },
                  context_instance=RequestContext(request))
Example #12
0
def add_event(request, name):
    """Render and process a form for users to create new rush events.

    Required parameters:
        - name  =>  the unique name (abbreviation) of the rush to which the new event should belong (as a string)

    """
    log_page_view(request, 'Add Rush Event')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = RushEventForm(request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.rush = rush
            event.save()
            rush.updated = datetime.now()
            rush.save()
            return _get_redirect_from_rush(rush)
    else:
        form = RushEventForm(initial={'rush': rush})
    return render(request,
                  'rush/add_event.html', {
                      'rush': rush,
                      'form': form
                  },
                  context_instance=RequestContext(request))
Example #13
0
def info_card_list(request):
    """Render a listing of all information cards that have been submitted to the chapter."""
    log_page_view(request, 'Info Card List')
    return render(request,
                  'rush/infocard_list.html',
                  {'cards': InformationCard.objects.all()},
                  context_instance=RequestContext(request))
Example #14
0
def edit_potential(request, id):
    """Render and process a form for users to modify information about an existing potential.

    Required parameters:
        - id    =>  the unique ID of the potential to edit (as an integer)

    """
    log_page_view(request, 'Edit Potential')
    potential = get_object_or_404(Potential, id=id)
    if request.method == 'POST':
        form = PotentialForm(request.POST, instance=potential)
        if form.is_valid():
            form.save()
            if form.cleaned_data['pledged']:
                redirect = reverse('show_pledge', kwargs={'id': id})
            else:
                redirect = reverse('show_potential', kwargs={'id': id})
            return HttpResponseRedirect(redirect)
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            if potential.rush:
                redirect = reverse('potentials', kwargs={'name': potential.rush.get_unique_name()})
            else:
                redirect = reverse('all_potentials')
            log.info('%s (%s) deleted potential %s %s', request.user.username, request.user.get_full_name(),
                     potential.first_name, potential.last_name)
            potential.delete()
            return HttpResponseRedirect(redirect)
        form = PotentialForm(instance=potential)
    return render(request, 'rush/edit_potential.html', {'form': form, 'potential': potential, 'pledge': False},
                  context_instance=RequestContext(request))
Example #15
0
def home(request):
    """Render a home page - a page of text for visitors and a sort of 'dashboard' view for authenticated members."""
    log_page_view(request, 'Home')
    if request.user.is_anonymous():
        template = 'index.html'
        context = {}  # main index doesn't require any context
    else:
        template = 'index_bros_only.html'
        user = request.user
        profile = user.get_profile()
        threads = profile.subscriptions.order_by('-updated')
        if len(threads) > 5:
            threads = threads[:5]
        announcements = Announcement.most_recent(False)
        two_months_ago = datetime.now() - timedelta(days=60)
        info_cards = InformationCard.objects.filter(
            created__gte=two_months_ago).order_by('-created')
        if len(info_cards) > 5:
            info_cards = info_cards[:5]
        accounts = UserProfile.objects.filter(
            user__date_joined__gte=two_months_ago).order_by('badge')
        context = {
            'subscriptions': threads,
            'announcements': announcements,
            'info_cards': info_cards,
            'accounts': accounts
        }
    return render(request,
                  template,
                  context,
                  context_instance=RequestContext(request))
Example #16
0
def edit_forum(request, slug):
    """Render and process a form to modify an existing forum.

    Required arguments:
        - slug  =>  the slug of the forum to edit (as a string)

    If 'delete=true' appears in the request's query string, the forum will be deleted, along with all of its threads.

    """
    log_page_view(request, 'Edit Forum')
    forum = get_object_or_404(Forum, slug=slug)
    profile = request.user.get_profile()
    if profile not in forum.moderators.all() and not profile.is_admin():
        return HttpResponseRedirect(reverse('forbidden'))
    if request.method == 'POST':
        form = ForumForm(request.POST, instance=forum)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('forums'))
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            log.info('%s (%s) deleted forum \'%s\'', request.user.username,
                     request.user.get_full_name(), forum.name)
            forum.delete()
            return HttpResponseRedirect(reverse('forums'))
        form = ForumForm(instance=forum)
    return render(request,
                  'forums/add_forum.html', {
                      'form': form,
                      'forum': forum,
                      'create': False
                  },
                  context_instance=RequestContext(request))
Example #17
0
def add_office_history(request, office):
    """Render and process a form to create a new officer history record.

    Required parameters:
        - office    =>  the abbreviation of the office whose history to add as a string (e.g., 'GP')

    """
    log_page_view(request, 'Add Office History')
    title = _get_office_title_or_404(office)
    if request.method == 'POST':
        form = OfficerHistoryForm(request.POST)
        if form.is_valid():
            history = form.save(commit=False)
            history.office = office
            history.save()
            log.info('%s (%s) added history for %s: %s (#%d), %s - %s',
                     request.user.username,
                     request.user.get_full_name(), office,
                     history.brother.common_name(), history.brother.badge,
                     history.start.strftime('%m/%d/%Y'),
                     history.end.strftime('%m/%d/%Y'))
            return HttpResponseRedirect(
                reverse('office_history', kwargs={'office': office}))
    else:
        form = OfficerHistoryForm()
    return render(request,
                  'officers/add_office_history.html', {
                      'office': title,
                      'abbrev': office,
                      'form': form
                  },
                  context_instance=RequestContext(request))
Example #18
0
def edit_event(request, id):
    """Render and process a form for users to modify an existing rush event.

    Required parameters:
        - id    =>  the unique ID of the rush event to edit (as an integer)

    """
    log_page_view(request, 'Edit Rush Event')
    event = get_object_or_404(RushEvent, id=id)
    if request.method == 'POST':
        form = RushEventForm(request.POST, instance=event)
        if form.is_valid():
            form.save()
            rush = event.rush
            rush.updated = datetime.now()
            rush.save()
            return _get_redirect_from_rush(rush)
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            log.info('%s (%s) deleted event \'%s\' from %s', request.user.username, request.user.get_full_name(),
                     event.title, event.rush.title())
            event.delete()
            return _get_redirect_from_rush(event.rush)
        form = RushEventForm(instance=event)
    return render(request, 'rush/edit_event.html', {'event_id': event.id, 'form': form},
                  context_instance=RequestContext(request))
Example #19
0
def edit(request, name):
    """Render and process a form for users to modify an existing rush.

    Required parameters:
        - name  =>  the unique name (abbreviation) of the rush to edit (as a string)

    """
    log_page_view(request, 'Edit Rush')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = RushForm(request.POST, instance=rush)
        if form.is_valid():
            form.save()
            return _get_redirect_from_rush(rush)
    else:
        if 'visible' in request.GET and request.GET.get('visible') == 'true':
            rush.visible = True
            rush.save()
            return _get_redirect_from_rush(rush)
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            name = rush.title()
            rush.delete()
            log.info('%s (%s) deleted %s', request.user.username, request.user.get_full_name(), name)
            return HttpResponseRedirect(reverse('rush_list'))
        form = RushForm(instance=rush)
    return render(request, 'rush/edit.html', {'rush_name': name, 'form': form}, context_instance=RequestContext(request))
Example #20
0
def view_thread(request, forum, id, thread, page=1):
    """Render a specific page of a thread.

    Required arguments:
        - forum     =>  the slug of the forum to which the thread belongs (as a string)
        - id        =>  the unique ID of the thread to view (as an integer)
        - thread    =>  the slug of the thread to view (as a string)

    Optional arguments:
        - page  =>  the number of the page to view (as an integer): defaults to 1

    """

    log_page_view(request, 'View Thread')
    forum = get_object_or_404(Forum, slug=forum)
    thread = get_object_or_404(Thread, id=id)
    objects = Post.objects.filter(thread=thread).order_by('number')
    paginator = Paginator(objects, settings.POSTS_PER_PAGE)

    try:
        posts = paginator.page(int(page))
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)

    profile = request.user.get_profile()
    is_mod = (profile in forum.moderators.all())
    subscribed = (profile in thread.subscribers.all())

    if subscribed and 'unsubscribe' in request.GET:
        profile.subscriptions.remove(thread)
        profile.save()
        return HttpResponseRedirect(
            reverse('view_thread_page',
                    kwargs={
                        'forum': forum.slug,
                        'id': thread.id,
                        'thread': thread.slug,
                        'page': page
                    }))
    elif not subscribed and 'subscribe' in request.GET:
        profile.subscriptions.add(thread)
        profile.save()
        return HttpResponseRedirect(
            reverse('view_thread_page',
                    kwargs={
                        'forum': forum.slug,
                        'id': thread.id,
                        'thread': thread.slug,
                        'page': page
                    }))

    return render(request,
                  'forums/view_thread.html', {
                      'thread': thread,
                      'posts': posts,
                      'forum': forum,
                      'subscribed': subscribed,
                      'is_mod': is_mod
                  },
                  context_instance=RequestContext(request))
Example #21
0
def announcements(request):
    """Render a listing of announcements posted by members of the chapter."""

    log_page_view(request, 'Announcement List')
    private = False
    if request.user.is_authenticated():
        if 'bros_only' in request.GET and request.GET['bros_only'] == 'true':
            objects = Announcement.objects.filter(public=False)
            private = True
        else:
            objects = Announcement.objects.all()
        template = 'chapter/announcements_bros_only.html'
    else:
        objects = Announcement.objects.filter(public=True)
        template = 'chapter/announcements.html'

    paginator = Paginator(objects, settings.ANNOUNCEMENTS_PER_PAGE)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1  # if 'page' parameter is not an integer, default to page 1
    try:
        announcements = paginator.page(page)
    except (EmptyPage, InvalidPage):
        announcements = paginator.page(paginator.num_pages)

    return render(request,
                  template, {
                      'announcements': announcements,
                      'private': private
                  },
                  context_instance=RequestContext(request))
Example #22
0
def update_potentials(request, name=None):
    """Process a request to modify several potential members simultaneously.

    Optional parameters:
        - name  =>  the unique name of the rush with which the potentials are associated (as a string): defaults to none

    """
    log_page_view(request, 'Update Potentials')
    if request.method != 'POST':
        return HttpResponseRedirect(reverse('forbidden'))
    action = request.POST.get('action', '')
    if action in ['hide', 'pledge', 'delete']:
        potentials = Potential.objects.filter(id__in=[int(potential) for potential in request.POST.getlist('potential')])
        count = potentials.count()
        if action == 'hide':
            potentials.update(hidden=True)
            log.info('%s (%s) marked %d potentials as hidden', request.user.username, request.user.get_full_name(), count)
        elif action == 'pledge':
            potentials.update(pledged=True)
            log.info('%s (%s) marked %d potentials as pledges', request.user.username, request.user.get_full_name(), count)
        else:   # action == 'delete'
            potentials.delete()
            log.info('%s (%s) deleted %d potentials', request.user.username, request.user.get_full_name(), count)
    rush = _get_rush_or_404(name)
    redirect = reverse('all_potentials') if rush is None else reverse('potentials', kwargs={'name': name})
    return HttpResponseRedirect(redirect)
Example #23
0
def office_history(request, office):
    """Render a listing of brothers who have held an officer position in the past, including the current officer.

    Required parameters:
        - office    =>  the abbreviation of the office whose history to view as a string (e.g., 'GP')

    """

    log_page_view(request, 'Office History')
    title = _get_office_title_or_404(office)

    history = []
    try:
        current = ChapterOfficer.objects.get(office=office)
    except ChapterOfficer.DoesNotExist:
        pass
    else:
        history.append((current.brother, current.updated, None))

    has_more = (OfficerHistory.objects.filter(office=office).count() > 9)
    show_all = (has_more and 'full' in request.GET and request.GET.get('full') == 'true')
    if has_more and show_all:
        old_officers = OfficerHistory.objects.filter(office=office).order_by('-end')
        has_more = False
    else:
        old_officers = OfficerHistory.objects.filter(office=office).order_by('-end')[:9]
    for officer in old_officers:
        history.append((officer.brother, officer.start, officer.end))

    return render(request, 'officers/office_history.html',
                  {'office': title, 'history': history, 'more': has_more, 'abbrev': office},
                  context_instance=RequestContext(request))
Example #24
0
def show(request, badge):
    """Render a display of information about a specific member of the chapter.

    Required parameters:
        - badge =>  the badge number of the brother to view (as an integer)

    """
    log_page_view(request, 'View Profile')
    try:
        profile = UserProfile.objects.get(badge=badge)
        user = profile.user
    except UserProfile.DoesNotExist:
        name = get_name_from_badge(int(badge))
        if name is None:
            raise Http404
        min = _get_lowest_undergrad_badge()
        status = 'Undergraduate' if int(badge) > min else 'Alumnus'
        context = {'account': None, 'name': name, 'badge': badge, 'status': status}
    else:
        show_public = ('public' in request.GET and request.GET.get('public') == 'true') or request.user.is_anonymous()
        visibility = profile.public_visibility if show_public else profile.chapter_visibility
        fields = _get_fields_from_profile(profile, visibility)
        chapter_fields, personal_fields, contact_fields = _get_field_categories(fields)
        big_bro = None
        if 'Big brother' in fields:
            try:
                big_bro = '%s ... %d' % (UserProfile.objects.get(badge=profile.big_brother).common_name(), int(profile.big_brother))
            except UserProfile.DoesNotExist:    # if user's big brother doesn't have an account, look up name by badge
                big_bro = '%s ... %d' % (get_name_from_badge(profile.big_brother), int(profile.big_brother))
        context = {'own_account': (user == request.user), 'account': user, 'profile': profile, 'public': show_public,
                   'big': big_bro, 'fields': fields, 'chapter_fields': chapter_fields, 'personal_fields': personal_fields,
                   'contact_fields': contact_fields}
    return render(request, 'brothers/show.html', context, context_instance=RequestContext(request))
Example #25
0
def edit(request, name):
    """Render and process a form for users to modify an existing rush.

    Required parameters:
        - name  =>  the unique name (abbreviation) of the rush to edit (as a string)

    """
    log_page_view(request, 'Edit Rush')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = RushForm(request.POST, instance=rush)
        if form.is_valid():
            form.save()
            return _get_redirect_from_rush(rush)
    else:
        if 'visible' in request.GET and request.GET.get('visible') == 'true':
            rush.visible = True
            rush.save()
            return _get_redirect_from_rush(rush)
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            name = rush.title()
            rush.delete()
            log.info('%s (%s) deleted %s', request.user.username,
                     request.user.get_full_name(), name)
            return HttpResponseRedirect(reverse('rush_list'))
        form = RushForm(instance=rush)
    return render(request,
                  'rush/edit.html', {
                      'rush_name': name,
                      'form': form
                  },
                  context_instance=RequestContext(request))
Example #26
0
def add_pledge(request, name=None):
    """Render and process a form for users to create records of new pledges.

    Optional parameters:
        - name  =>  the unique name (abbreviation) of the rush with which to associate the pledge: defaults to none

    """
    log_page_view(request, 'Add Pledge')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = PledgeForm(request.POST)
        if form.is_valid():
            pledge = form.save(commit=False)
            pledge.pledged = True
            pledge.save()
            if rush is None:
                redirect = reverse('all_pledges')
            else:
                rush.updated = datetime.now()
                rush.save()
                redirect = reverse('pledges', kwargs={'name': name})
            return HttpResponseRedirect(redirect)
    else:
        form = PledgeForm() if rush is None else PledgeForm(initial={'rush': rush})
    return render(request, 'rush/add_potential.html', {'form': form, 'rush': rush, 'pledge': True},
                  context_instance=RequestContext(request))
Example #27
0
def edit_event(request, id):
    """Render and process a form for users to modify an existing rush event.

    Required parameters:
        - id    =>  the unique ID of the rush event to edit (as an integer)

    """
    log_page_view(request, 'Edit Rush Event')
    event = get_object_or_404(RushEvent, id=id)
    if request.method == 'POST':
        form = RushEventForm(request.POST, instance=event)
        if form.is_valid():
            form.save()
            rush = event.rush
            rush.updated = datetime.now()
            rush.save()
            return _get_redirect_from_rush(rush)
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            log.info('%s (%s) deleted event \'%s\' from %s',
                     request.user.username, request.user.get_full_name(),
                     event.title, event.rush.title())
            event.delete()
            return _get_redirect_from_rush(event.rush)
        form = RushEventForm(instance=event)
    return render(request,
                  'rush/edit_event.html', {
                      'event_id': event.id,
                      'form': form
                  },
                  context_instance=RequestContext(request))
Example #28
0
def edit_pledge(request, id):
    """Render and process a form for users to modify information about an existing pledge.

    Required parameters:
        - id    =>  the unique ID of the pledge to edit (as an integer)

    """
    log_page_view(request, 'Edit Pledge')
    pledge = get_object_or_404(Potential, id=id)
    if request.method == 'POST':
        form = PledgeForm(request.POST, instance=pledge)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(pledge.get_absolute_url())
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            if pledge.rush:
                redirect = reverse('pledges', kwargs={'name': pledge.rush.get_unique_name()})
            else:
                redirect = reverse('all_pledges')
            log.info('%s (%s) deleted pledge %s %s', request.user.username, request.user.get_full_name(),
                     pledge.first_name, pledge.last_name)
            pledge.delete()
            return HttpResponseRedirect(redirect)
        form = PledgeForm(instance=pledge)
    return render(request, 'rush/edit_potential.html', {'form': form, 'potential': pledge, 'pledge': True},
                  context_instance=RequestContext(request))
Example #29
0
def potentials(request, name=None):
    """Render a listing of potential members, including all potentials or only those from a specific rush.

    Optional parameters:
        - name => the unique name (abbreviation) of the rush for which to show potentials (as a string): defaults to all

    """
    log_page_view(request, 'Potentials')
    rush = _get_rush_or_404(name)
    if 'all' in request.GET and request.GET.get('all') == 'true':
        hidden = 0
    else:
        hidden = Potential.objects.filter(pledged=False, hidden=True).count()
    descending = (request.GET.get('order',
                                  '') == 'desc')  # ascending order by default
    potentials = _get_potential_queryset(hidden == 0, rush, False,
                                         request.GET.get('sort', 'name'),
                                         descending)
    current_rush = None if Rush.current() is None else Rush.current(
    ).get_unique_name()
    return render(request,
                  'rush/potentials.html', {
                      'potentials': potentials,
                      'rush': rush,
                      'hidden': hidden,
                      'current_rush': current_rush
                  },
                  context_instance=RequestContext(request))
Example #30
0
def schedule(request):
    """Render a schedule of events for the current rush."""
    log_page_view(request, 'Rush Schedule')
    current_rush = Rush.current()
    if current_rush is None:
        raise Http404
    return render(request, 'rush/schedule.html', {'rush': current_rush}, context_instance=RequestContext(request))
Example #31
0
def edit_forum(request, slug):
    """Render and process a form to modify an existing forum.

    Required arguments:
        - slug  =>  the slug of the forum to edit (as a string)

    If 'delete=true' appears in the request's query string, the forum will be deleted, along with all of its threads.

    """
    log_page_view(request, 'Edit Forum')
    forum = get_object_or_404(Forum, slug=slug)
    profile = request.user.get_profile()
    if profile not in forum.moderators.all() and not profile.is_admin():
        return HttpResponseRedirect(reverse('forbidden'))
    if request.method == 'POST':
        form = ForumForm(request.POST, instance=forum)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('forums'))
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            log.info('%s (%s) deleted forum \'%s\'', request.user.username, request.user.get_full_name(), forum.name)
            forum.delete()
            return HttpResponseRedirect(reverse('forums'))
        form = ForumForm(instance=forum)
    return render(request, 'forums/add_forum.html', {'form': form, 'forum': forum, 'create': False},
                  context_instance=RequestContext(request))
Example #32
0
def edit_officer(request, office):
    """Render and process a form to modify which brother currently holds an officer position.

    Required parameters:
        - office    =>  the abbreviation of the office to edit as a string (e.g., 'GP')

    """

    log_page_view(request, 'Edit Officer')
    title = _get_office_title_or_404(office)

    if request.method == 'POST':
        form = OfficerForm(request.POST)
        if form.is_valid():
            brother = form.cleaned_data.get('brother')
            try:
                prev = ChapterOfficer.objects.get(office=office)
            except ChapterOfficer.DoesNotExist:     # this shouldn't happen, but handle it just in case
                officer = ChapterOfficer.objects.create(office=office, brother=brother, updated=date.today())
                officer.save()
            else:
                if prev.brother != brother:
                    history = OfficerHistory.objects.create(office=prev.office, brother=prev.brother, start=prev.updated, end=date.today())
                    history.save()
                    prev.brother = brother  # just update the existing officer record instead of deleting and recreating
                    prev.updated = date.today()
                    prev.save()
                    log.info('%s (%s) changed %s from %s (#%d) to %s (#%d)', request.user.username, request.user.get_full_name(),
                             office, history.brother.common_name(), history.brother.badge, brother.common_name(), brother.badge)
            return HttpResponseRedirect(reverse('show_officers'))
    else:
        form = OfficerForm()

    return render(request, 'officers/edit_officer.html', {'form': form, 'title': title, 'office': office},
                  context_instance=RequestContext(request))
Example #33
0
def forgot_password(request):
    """Render and process a form to allow users to reset their passwords."""

    log_page_view(request, 'Forgot Password')
    if request.user.is_authenticated(
    ) and not request.user.get_profile().is_admin():
        return HttpResponseRedirect(
            reverse('forbidden')
        )  # if you're logged in but not admin, you shouldn't be here

    username = None
    if request.method == 'POST':
        username = request.POST.get('username', '')
    elif 'username' in request.session and request.session['username'] != '':
        username = request.session['username']

    if username is None:
        error = None
    else:
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            error = 'That username is invalid.'
        else:
            return reset_password(request, user.id)

    return render(request,
                  'public/forgot_password.html', {'error': error},
                  context_instance=RequestContext(request))
Example #34
0
def pledges(request, name=None):
    """Render a listing of pledges, either all pledges or only those from a specific rush (semester).

    Optional parameters:
        - name => the unique name (abbreviation) of the rush to which to restrict the listing; defaults to all rushes

    """
    log_page_view(request, 'Pledges')
    rush = _get_rush_or_404(name)
    if rush is not None or ('all' in request.GET
                            and request.GET.get('all') == 'true'):
        hidden = 0
    else:
        hidden = Potential.objects.filter(hidden=True).count()
    descending = (request.GET.get('order',
                                  '') == 'desc')  # ascending order by default
    pledges = _get_potential_queryset(hidden == 0, rush, True,
                                      request.GET.get('sort', 'name'),
                                      descending)
    current_rush = None if Rush.current() is None else Rush.current(
    ).get_unique_name()
    return render(request,
                  'rush/pledges.html', {
                      'pledges': pledges,
                      'hidden': hidden,
                      'rush': rush,
                      'current_rush': current_rush
                  },
                  context_instance=RequestContext(request))
Example #35
0
def change_password(request):
    """Render and process a form for the currently authenticated user to change his password."""

    log_page_view(request, 'Change Password')
    user = request.user
    profile = user.get_profile()
    reset = profile.has_bit(STATUS_BITS['PASSWORD_RESET'])

    if request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        form.user = user
        if form.is_valid():
            user.set_password(form.cleaned_data['password'])
            user.save()
            if reset:
                profile.clear_bit(STATUS_BITS['PASSWORD_RESET'])
                profile.save()
            else:
                send_mail(get_message('email.new_password.subject'),
                          get_message('email.new_password.body', args=(user.first_name,)),
                          settings.EMAIL_HOST_USER, [user.email])
            log.info('User %s (%s) changed his password', user.username, user.get_full_name())
            return HttpResponseRedirect(reverse('change_password_success'))
    else:
        form = ChangePasswordForm()
        form.user = user

    return render(request, 'brothers/change_password.html',
                  {'form': form, 'message': (get_message('profile.password.reset') if reset else None)},
                  context_instance=RequestContext(request))
Example #36
0
def forbidden(request):
    """Render a 'forbidden' page when a user tries to go to a page that he is not allowed to view."""
    log_page_view(request, 'Forbidden')
    log.info('Forbidden action attempted!')
    return render(request,
                  'forbidden.html',
                  context_instance=RequestContext(request))
Example #37
0
def add_group(request):
    """Render and process a form to create a new user group."""
    log_page_view(request, 'Add User Group')
    error = None
    initial_name = ''   # empty string, not None (otherwise 'None' will appear in the form input)
    if request.method == 'POST':
        ids = []
        group_name = None
        for name, value in request.POST.items():
            if name.find('perm_') > -1:
                ids.append(int(value))
            elif name == 'group_name':      # validate group names for format and uniqueness
                initial_name = value
                if match(r'^[a-zA-Z0-9_]+[a-zA-Z0-9_ ]*[a-zA-Z0-9]+$', value) is None:
                    error = get_message('group.name.invalid')
                elif Group.objects.filter(name=value).count() > 0:
                    error = get_message('group.name.exists')
                else:
                    group_name = value
        if error is None:
            if group_name is None:
                error = get_message('group.name.nonempty')
            elif not len(ids):
                error = get_message('group.perms.nonempty')
            else:
                group = Group.objects.create(name=group_name)
                group.permissions = Permission.objects.filter(id__in=ids)
                group.save()
                log.info('%s (%s) created user group \'%s\'', request.user.username, request.user.get_full_name(), group_name)
                return HttpResponseRedirect(reverse('view_group', kwargs={'name': group.name}))
    perms = _get_available_permissions()
    choices = [[perm.id, perm.name] for perm in perms]
    return render(request, 'brothers/add_group.html', {'error': error, 'name': initial_name, 'perms': choices},
                  context_instance=RequestContext(request))
Example #38
0
def edit_group_perms(request, id):
    """Render and process a form to modify the permissions associated with a user group.

    Required parameters:
        - id  =>  the unique ID of the group to edit (as an integer)

    """
    log_page_view(request, 'Edit Group Permissions')
    group = get_object_or_404(Group, id=id)
    if request.method == 'POST':
        ids = []
        for name, value in request.POST.items():
            if name.find('perm_') > -1:
                ids.append(int(value))
        group.permissions = Permission.objects.filter(id__in=ids)
        group.save()
        del request.session['group_perms']  # clear existing group permissions in case they just changed
        log.info('%s (%s) edited permissions for group \'%s\'', request.user.username, request.user.get_full_name(), group.name)
        return HttpResponseRedirect(reverse('view_group', kwargs={'id': group.id}))
    else:
        perms = _get_available_permissions()
        group_perms = group.permissions.all()
        choices = []
        initial = []
        for perm in perms:
            choices.append([perm.id, perm.name])
            if perm in group_perms:
                initial.append(perm.id)
    return render(request, 'brothers/edit_group_perms.html',
                  {'group': group, 'perms': choices, 'initial': initial},
                  context_instance=RequestContext(request))
Example #39
0
def edit_pledge(request, id):
    """Render and process a form for users to modify information about an existing pledge.

    Required parameters:
        - id    =>  the unique ID of the pledge to edit (as an integer)

    """
    log_page_view(request, 'Edit Pledge')
    pledge = get_object_or_404(Potential, id=id)
    if request.method == 'POST':
        form = PledgeForm(request.POST, instance=pledge)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(pledge.get_absolute_url())
    else:
        if 'delete' in request.GET and request.GET.get('delete') == 'true':
            if pledge.rush:
                redirect = reverse(
                    'pledges', kwargs={'name': pledge.rush.get_unique_name()})
            else:
                redirect = reverse('all_pledges')
            log.info('%s (%s) deleted pledge %s %s', request.user.username,
                     request.user.get_full_name(), pledge.first_name,
                     pledge.last_name)
            pledge.delete()
            return HttpResponseRedirect(redirect)
        form = PledgeForm(instance=pledge)
    return render(request,
                  'rush/edit_potential.html', {
                      'form': form,
                      'potential': pledge,
                      'pledge': True
                  },
                  context_instance=RequestContext(request))
Example #40
0
def add_pledge(request, name=None):
    """Render and process a form for users to create records of new pledges.

    Optional parameters:
        - name  =>  the unique name (abbreviation) of the rush with which to associate the pledge: defaults to none

    """
    log_page_view(request, 'Add Pledge')
    rush = _get_rush_or_404(name)
    if request.method == 'POST':
        form = PledgeForm(request.POST)
        if form.is_valid():
            pledge = form.save(commit=False)
            pledge.pledged = True
            pledge.save()
            if rush is None:
                redirect = reverse('all_pledges')
            else:
                rush.updated = datetime.now()
                rush.save()
                redirect = reverse('pledges', kwargs={'name': name})
            return HttpResponseRedirect(redirect)
    else:
        form = PledgeForm() if rush is None else PledgeForm(
            initial={'rush': rush})
    return render(request,
                  'rush/add_potential.html', {
                      'form': form,
                      'rush': rush,
                      'pledge': True
                  },
                  context_instance=RequestContext(request))
Example #41
0
def sign_out(request):
    """Sign out the currently authenticated user (if there is one), then redirect to the home page."""
    log_page_view(request, 'Sign Out')
    log.info('User %s (%s) signed out', request.user.username, request.user.get_full_name())
    logout(request)
    if 'group_perms' in request.session:
        del request.session['group_perms']
    return HttpResponseRedirect(reverse('home'))
Example #42
0
def add_post(request, forum, id, thread):
    """Render and process a form to create a new post.

    Required arguments:
        - forum     =>  the slug of the forum to which the new post's thread belongs (as a string)
        - id        =>  the unique ID of the thread to which the new post should belong (as an integer)
        - thread    =>  the slug of the thread to which the new post should belong (as a string)

    """

    log_page_view(request, 'Reply to Thread')
    forum = get_object_or_404(Forum, slug=forum)
    thread = get_object_or_404(Thread, id=id)

    if request.method == 'POST':
        quote = None
        if 'quote' in request.POST:
            try:
                quote = Post.objects.get(thread=thread,
                                         number=int(request.POST.get('quote')))
            except Post.DoesNotExist:
                pass
        form = PostForm(request.POST)
        if form.is_valid():
            profile = request.user.get_profile()
            post = form.save(commit=False)
            post.thread = thread
            post.user = profile
            post.updated_by = profile
            post.deleted = False
            post.number = Post.objects.filter(thread=thread).count() + 1
            if quote is not None:
                post.quote = quote
            post.body = _bb_code_escape(post.body)
            post.save()
            thread.updated = datetime.now()
            thread.save(
            )  # set the thread's updated time to now, since the thread has a new post
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        quote = None
        if 'quote' in request.GET:
            try:
                quote = Post.objects.get(thread=thread,
                                         number=int(request.GET.get('quote')))
            except Post.DoesNotExist:
                pass
        form = PostForm()

    return render(request,
                  'forums/add_post.html', {
                      'form': form,
                      'forum': forum,
                      'thread': thread,
                      'quote': quote,
                      'create': True
                  },
                  context_instance=RequestContext(request))
Example #43
0
def visibility(request):
    """Render a display of the currently authenticated user's visibility settings, both public and private."""
    log_page_view(request, 'Visibility Settings')
    profile = request.user.get_profile()
    public = profile.public_visibility
    chapter = profile.chapter_visibility
    fields = _get_fields_from_profile(profile)
    return render(request, 'brothers/visibility.html', {'fields': fields, 'public': public, 'chapter': chapter},
                  context_instance=RequestContext(request))
Example #44
0
def list(request):
    """Render a listing of all members of the chapter, separating undergraduates from alumni."""
    log_page_view(request, 'Brother List')
    columns = 3
    undergrad_rows, num_undergrads = _get_brother_listing(num_cols=columns)
    alumni_rows, num_alumni = _get_brother_listing(False, columns)
    return render(request, 'brothers/list.html',
                  {'undergrad_rows': undergrad_rows, 'num_undergrads': num_undergrads, 'alumni_rows': alumni_rows, 'col_width': 100/columns},
                  context_instance=RequestContext(request))
Example #45
0
def schedule(request):
    """Render a schedule of events for the current rush."""
    log_page_view(request, 'Rush Schedule')
    current_rush = Rush.current()
    if current_rush is None:
        raise Http404
    return render(request,
                  'rush/schedule.html', {'rush': current_rush},
                  context_instance=RequestContext(request))
Example #46
0
def sign_out(request):
    """Sign out the currently authenticated user (if there is one), then redirect to the home page."""
    log_page_view(request, 'Sign Out')
    log.info('User %s (%s) signed out', request.user.username,
             request.user.get_full_name())
    logout(request)
    if 'group_perms' in request.session:
        del request.session['group_perms']
    return HttpResponseRedirect(reverse('home'))
Example #47
0
def info_card_show(request, id):
    """Render a display of information about a particular information card.

    Required parameters:
        - id    =>  the unique ID of the information card to view (as an integer)

    """
    log_page_view(request, 'View Info Card')
    card = get_object_or_404(InformationCard, id=id)
    return render(request, 'rush/infocard_show.html', {'card': card}, context_instance=RequestContext(request))
Example #48
0
def show_potential(request, id):
    """Render a display of information about a potential member.

    Required parameters:
        - id    =>  the unique ID of the potential to view (as an integer)

    """
    log_page_view(request, 'View Potential')
    potential = get_object_or_404(Potential, id=id)
    return render(request, 'rush/potential_show.html', {'potential': potential}, context_instance=RequestContext(request))
Example #49
0
def show_pledge(request, id):
    """Render a display of information about a particular pledge.

    Required parameter:
        - id    => the unique ID of the pledge to view (as an integer)

    """
    log_page_view(request, 'View Pledge')
    pledge = get_object_or_404(Potential, id=id)
    return render(request, 'rush/potential_show.html', {'potential': pledge}, context_instance=RequestContext(request))
Example #50
0
def old_schedule(request):
    """Render a schedule of events for the current rush (exactly the same as the 'schedule' view).

    For backward compatibility, we need to support the URI '/rushschedule.php'. We also want there to be a distinct
    (and clean) URI for the rush schedule, i.e., reverse('rush_schedule') should resolve successfully. So, we use this
    view as a pass-through to convert the old URI to the new one.

    """
    log_page_view(request, 'Old Rush Schedule')
    return HttpResponseRedirect(reverse('rush_schedule'))
Example #51
0
def old_schedule(request):
    """Render a schedule of events for the current rush (exactly the same as the 'schedule' view).

    For backward compatibility, we need to support the URI '/rushschedule.php'. We also want there to be a distinct
    (and clean) URI for the rush schedule, i.e., reverse('rush_schedule') should resolve successfully. So, we use this
    view as a pass-through to convert the old URI to the new one.

    """
    log_page_view(request, 'Old Rush Schedule')
    return HttpResponseRedirect(reverse('rush_schedule'))
Example #52
0
def show(request, badge):
    """Render a display of information about a specific member of the chapter.

    Required parameters:
        - badge =>  the badge number of the brother to view (as an integer)

    """
    log_page_view(request, 'View Profile')
    try:
        profile = UserProfile.objects.get(badge=badge)
        user = profile.user
    except UserProfile.DoesNotExist:
        name = get_name_from_badge(int(badge))
        if name is None:
            raise Http404
        min = _get_lowest_undergrad_badge()
        status = 'Undergraduate' if int(badge) > min else 'Alumnus'
        context = {
            'account': None,
            'name': name,
            'badge': badge,
            'status': status
        }
    else:
        show_public = ('public' in request.GET and request.GET.get('public')
                       == 'true') or request.user.is_anonymous()
        visibility = profile.public_visibility if show_public else profile.chapter_visibility
        fields = _get_fields_from_profile(profile, visibility)
        chapter_fields, personal_fields, contact_fields = _get_field_categories(
            fields)
        big_bro = None
        if 'Big brother' in fields:
            try:
                big_bro = '%s ... %d' % (UserProfile.objects.get(
                    badge=profile.big_brother).common_name(),
                                         int(profile.big_brother))
            except UserProfile.DoesNotExist:  # if user's big brother doesn't have an account, look up name by badge
                big_bro = '%s ... %d' % (get_name_from_badge(
                    profile.big_brother), int(profile.big_brother))
        context = {
            'own_account': (user == request.user),
            'account': user,
            'profile': profile,
            'public': show_public,
            'big': big_bro,
            'fields': fields,
            'chapter_fields': chapter_fields,
            'personal_fields': personal_fields,
            'contact_fields': contact_fields
        }
    return render(request,
                  'brothers/show.html',
                  context,
                  context_instance=RequestContext(request))
Example #53
0
def my_threads(request):
    """Render a listing of all threads belonging to the current user."""
    log_page_view(request, 'My Threads')
    threads = Thread.objects.filter(
        owner=request.user.get_profile()).order_by('-updated')
    return render(request,
                  'forums/subscriptions.html', {
                      'threads': threads,
                      'subscribe': False
                  },
                  context_instance=RequestContext(request))
Example #54
0
def subscriptions(request):
    """Render a listing of all threads to which the current user is subscribed."""
    log_page_view(request, 'Subscribed Threads')
    threads = request.user.get_profile().subscriptions.all().order_by(
        '-updated')
    return render(request,
                  'forums/subscriptions.html', {
                      'threads': threads,
                      'subscribe': True
                  },
                  context_instance=RequestContext(request))
Example #55
0
def reset_password(request, id):
    """Reset a user's password to a random string and email the user the new password.

    Required parameters:
        - id    =>  the unique ID of the user whose password should be reset (as an integer)

    """

    log_page_view(request, 'Reset Password')
    if request.user.is_authenticated(
    ) and not request.user.get_profile().is_admin():
        return HttpResponseRedirect(reverse(
            'forbidden'))  # non-admins should use the 'change password' form

    user = get_object_or_404(User, id=id)
    anonymous = request.user.is_anonymous()

    if request.method == 'POST':
        password = User.objects.make_random_password(
            length=8, allowed_chars=settings.PASSWORD_RESET_CHARS)
        user.set_password(password)
        user.save()
        profile = user.get_profile()
        profile.set_bit(STATUS_BITS['PASSWORD_RESET'])
        profile.save()

        reset_message = get_message('email.password.reset' if anonymous else
                                    'email.password.admin.reset')
        message = get_message('email.password.body',
                              args=(profile.preferred_name(), reset_message,
                                    password))
        user.email_user(get_message('email.password.subject'), message)

        if anonymous:
            log.info(
                'Password reset for %s (%s) - temporary password emailed to %s',
                user.username, user.get_full_name(), user.email)
            redirect = reverse('reset_password_success')
        else:
            log.info(
                'Admin %s (#%d) reset password for %s (%s) - temporary password emailed to %s',
                request.user.get_full_name(),
                request.user.get_profile().badge, user.username,
                user.get_full_name(), user.email)
            redirect = reverse('manage_users')
        return HttpResponseRedirect(redirect)

    return render(request,
                  'public/reset_password.html', {
                      'anon': anonymous,
                      'username': user.username,
                      'user_id': id
                  },
                  context_instance=RequestContext(request))
Example #56
0
def add(request):
    """Render and process a form for users to create new rushes."""
    log_page_view(request, 'Add Rush')
    if request.method == 'POST':
        form = RushForm(request.POST)
        if form.is_valid():
            rush = form.save()
            log.info('%s (%s) created %s', request.user.username, request.user.get_full_name(), rush.title())
            return HttpResponseRedirect(reverse('rush_list'))
    else:
        form = RushForm()
    return render(request, 'rush/create.html', {'form': form}, context_instance=RequestContext(request))
Example #57
0
def edit(request):
    """Render a form for the currently authenticated user to modify his user profile."""
    log_page_view(request, 'Edit Profile')
    profile = get_object_or_404(UserProfile, user=request.user)
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('my_profile'))
    else:
        form = EditProfileForm(instance=profile)
    return render(request, 'brothers/edit.html', {'form': form}, context_instance=RequestContext(request))
Example #58
0
def change_email(request):
    """Process a request from a user to change his email address, verifying the validity of the new email address."""
    log_page_view(request, 'Change Email')
    if 'hash' in request.GET:
        req = get_object_or_404(EmailChangeRequest, hash=request.GET.get('hash'))
        user = req.user
        log.info('Email address for %s (%s) changed from %s to %s', user.username, user.get_full_name(), user.email, req.email)
        user.email = req.email
        user.save()
        req.delete()    # to keep the email change request table as small as possible, delete requests as they are processed
        return HttpResponseRedirect(reverse('change_email_success'))
    return HttpResponseRedirect(reverse('home'))    # if 'hash' parameter not in query string, redirect to home page
Example #59
0
def show_pledge(request, id):
    """Render a display of information about a particular pledge.

    Required parameter:
        - id    => the unique ID of the pledge to view (as an integer)

    """
    log_page_view(request, 'View Pledge')
    pledge = get_object_or_404(Potential, id=id)
    return render(request,
                  'rush/potential_show.html', {'potential': pledge},
                  context_instance=RequestContext(request))
Example #60
0
def forums(request):
    """Render a listing of all forums, including the most recent post of all threads within each forum."""
    log_page_view(request, 'Forum List')
    forum_list = Forum.objects.all()
    forums = []
    for forum in forum_list:
        if Post.objects.filter(thread__forum=forum).count():
            last_post = Post.objects.filter(thread__forum=forum).order_by('-updated')[0]
        else:
            last_post = None
        forums.append((forum, last_post))
    return render(request, 'forums/forums.html', {'forums': forums}, context_instance=RequestContext(request))