<commit_before># -*- coding: utf-8 -*-
from django.conf import settings
from django.db.models import Count
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.template import loader, Context, RequestContext
from django.http import HttpResponse, HttpResponseRedirect, Http404

from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required

from djspace.application.forms import *
from djspace.application.models import ROCKET_LAUNCH_COMPETITION_TEAM_LIMIT
from djspace.application.models import ROCKET_LAUNCH_COMPETITION_WITH_LIMIT
from djspace.core.models import UserFiles
from djspace.core.utils import profile_status

from djtools.fields.helpers import handle_uploaded_file
from djtools.utils.convert import str_to_class
from djtools.utils.mail import send_mail
from djtools.fields import TODAY

import django
from os.path import join

@login_required
def application_form(request, application_type, aid=None):

    # our user
    user = request.user

    # verify that the user has completed registration
    reg_type = user.profile.registration_type
    try:
        mod = django.apps.apps.get_model(
            app_label='registration', model_name=reg_type
        )
        reg = mod.objects.get(user=user)
    except:
        # redirect to dashboard
        return HttpResponseRedirect(reverse('dashboard_home'))

    # verify that the user has an up to date registration
    if not profile_status(user):
        # redirect to dashboard
        return HttpResponseRedirect(reverse('dashboard_home'))

    # munge the application type
    slug_list = application_type.split("-")
    app_name = slug_list.pop(0).capitalize()
    for n in slug_list:
        app_name += " %s" % n.capitalize()
    app_type = "".join(app_name.split(" "))


    # check rocket competition teams and member limits.
    # currently, FNL does not have a limit so we can exclude it.
    if "rocket-competition" in application_type:
        teams = RocketLaunchTeam.objects.filter(
            competition__contains=app_name[:12]
        )

        if application_type != "first-nations-rocket-competition":
            teams = teams.annotate(
                count=Count('members')
            ).exclude(
                count__gte=ROCKET_LAUNCH_COMPETITION_TEAM_LIMIT
            ).order_by("name")

        if not teams:
            return render_to_response(
                "application/form.html",
                {"form": None,"app_name":app_name},
                context_instance=RequestContext(request)
            )

    # we need the application model now
    mod = django.apps.apps.get_model(
        app_label='application', model_name=app_type
    )

    # email distribution
    if settings.DEBUG:
        TO_LIST = [settings.ADMINS[0][1],]
    else:
        TO_LIST = [settings.WSGC_APPLICATIONS,]

    # fetch object if update
    app = None
    # initialise work plan tasks for industry internship
    tasks = None
    if aid:

        if user.is_superuser:
            app = get_object_or_404(mod, pk=aid)
        else:
            # prevent users from managing apps that are not theirs
            try:
                app = mod.objects.get(pk=aid, user=user)
            except:
                app = None

    # fetch the form class
    FormClass = str_to_class(
        "djspace.application.forms", (app_type+"Form")
    )
    # fetch the form instance

    # debugging
    form = FormClass(instance=app)
    '''
    try:
        form = FormClass(instance=app)
    except:
        # app_type does not match an existing form
        raise Http404
    '''
    # GET or POST
    if request.method == 'POST':
        try:
            # only rocket launch team form needs request context
            if application_type == "rocket-launch-team":
                form = FormClass(
                    instance=app, data=request.POST, files=request.FILES,
                    request=request
                )
            else:
                form = FormClass(<commit_msg>removed debugging code; redirect to dashboard home if user attempts to update an application that s/he does not own; redirect to dashboard home if app was created before the start of the current grant cycle<commit_after># -*- coding: utf-8 -*-
from django.conf import settings
from django.db.models import Count
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.template import loader, Context, RequestContext
from django.http import HttpResponse, HttpResponseRedirect, Http404

from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required

from djspace.application.forms import *
from djspace.application.models import ROCKET_LAUNCH_COMPETITION_TEAM_LIMIT
from djspace.application.models import ROCKET_LAUNCH_COMPETITION_WITH_LIMIT
from djspace.core.models import UserFiles
from djspace.core.utils import profile_status
from djspace.core.utils import get_start_date

from djtools.fields.helpers import handle_uploaded_file
from djtools.utils.convert import str_to_class
from djtools.utils.mail import send_mail
from djtools.fields import TODAY

import django
from os.path import join

@login_required
def application_form(request, application_type, aid=None):

    # our user
    user = request.user

    # verify that the user has completed registration
    reg_type = user.profile.registration_type
    try:
        mod = django.apps.apps.get_model(
            app_label='registration', model_name=reg_type
        )
        reg = mod.objects.get(user=user)
    except:
        # redirect to dashboard
        return HttpResponseRedirect(reverse('dashboard_home'))

    # verify that the user has an up to date registration
    if not profile_status(user):
        # redirect to dashboard
        return HttpResponseRedirect(reverse('dashboard_home'))

    # munge the application type
    slug_list = application_type.split("-")
    app_name = slug_list.pop(0).capitalize()
    for n in slug_list:
        app_name += " %s" % n.capitalize()
    app_type = "".join(app_name.split(" "))


    # check rocket competition teams and member limits.
    # currently, FNL does not have a limit so we can exclude it.
    if "rocket-competition" in application_type:
        teams = RocketLaunchTeam.objects.filter(
            competition__contains=app_name[:12]
        )

        if application_type != "first-nations-rocket-competition":
            teams = teams.annotate(
                count=Count('members')
            ).exclude(
                count__gte=ROCKET_LAUNCH_COMPETITION_TEAM_LIMIT
            ).order_by("name")

        if not teams:
            return render_to_response(
                "application/form.html",
                {"form": None,"app_name":app_name},
                context_instance=RequestContext(request)
            )

    # we need the application model now
    mod = django.apps.apps.get_model(
        app_label='application', model_name=app_type
    )

    # email distribution
    if settings.DEBUG:
        TO_LIST = [settings.ADMINS[0][1],]
    else:
        TO_LIST = [settings.WSGC_APPLICATIONS,]

    # fetch object if update
    app = None
    # initialise work plan tasks for industry internship
    tasks = None
    if aid:

        if user.is_superuser:
            app = get_object_or_404(mod, pk=aid)
        else:
            # prevent users from managing apps that are not theirs
            try:
                app = mod.objects.get(pk=aid, user=user)
            except:
                return HttpResponseRedirect(reverse('dashboard_home'))


        # verify that create_date is after grant cycle began
        # otherwise redirect to dashboard home
        if app.date_created < get_start_date():
            # redirect to dashboard
            return HttpResponseRedirect(reverse('dashboard_home'))


    # fetch the form class
    FormClass = str_to_class(
        "djspace.application.forms", (app_type+"Form")
    )
    # fetch the form instance
    try:
        form = FormClass(instance=app)
    except:
        # app_type does not match an existing form
        raise Http404
    # GET or POST
    if request.method == 'POST':
        try:
            # only rocket launch team form needs request context
            if application_type == "rocket-launch-team":
                form = FormClass(
                    instance=app, data=request.POST, files=request.FILES,
                    request=request
                )
            else:
                form = FormClass(
{'fraction_non_alphanumeric': 0.07546955036994878, 'fraction_numerical': 0.004097894137734775, 'mean_word_length': 2.609695973705834, 'pattern_counts': {'":': 8, '<': 4, '<?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': '1977937', 'n_tokens_mistral': 2482, 'n_tokens_neox': 2385, 'n_words': 671}