<commit_before># -*- coding: utf-8 -*-
from django.contrib.admin import site
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import get_model
from django.forms.models import modelform_factory
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.template.loader import get_template
from django.template import TemplateDoesNotExist
from django.utils.translation import ugettext
from django.views.decorators.cache import never_cache
from django.utils.importlib import import_module
from django.conf import settings
from django.forms import CharField

from forms import DeleteRequestForm, FrontendAdminModelForm

EXCLUDES = getattr(settings, 'FRONTEND_EXCLUDES', {})
FIELDS = getattr(settings, 'FRONTEND_FIELDS', {})
FORMS = getattr(settings, 'FRONTEND_FORMS', {})

def import_function(s):
    """
    Import a function given the string formatted as
    `module_name.function_name`  (eg `django.utils.text.capfirst`)
    """
    a = s.split('.')
    j = lambda x: '.'.join(x)
    return getattr(import_module(j(a[:-1])), a[-1])

def check_permission(request, mode_name, app_label, model_name):
    '''
    Check for proper permissions. mode_name may be either add, change or delete.
    '''
    p = '%s.%s_%s' % (app_label, mode_name, model_name)
    return request.user.is_active and request.user.has_perm(p)

def _get_instance(request, mode_name, app_label, model_name, instance_id=None,
                                            form=None,
                                            form_fields=None,
                                            form_exclude=None):
    '''
    Returns the model and an instance_form for the given arguments. If an primary
    key (instance_id) is given, it will return also the instance.

    If the user has no permission to add, change or delete the object, a
    HttpResponse is returned.
    '''
    # Check for permission to add/change/delete this object
    if not check_permission(request, mode_name, app_label, model_name):
        return HttpResponseForbidden('You have no permission to do this!')

    try:
        model = get_model(app_label, model_name)
    # Model does not exist
    except AttributeError:
        return HttpResponseForbidden('This model does not exist!')
    label = '%s.%s' % (app_label, model_name)
    # get form for model
    if label in FORMS and not form:
        form = import_function(FORMS[label])
    elif model in site._registry and not form:
        form = site._registry[model].form
    elif form is None:
        form = FrontendAdminModelForm
    
    if label in EXCLUDES:
        form_exclude = EXCLUDES[label]
    if label in FIELDS:
        form_fields = FIELDS[label]

    instance_form = modelform_factory(model, form=form,
                                      fields=form_fields, exclude=form_exclude)
    # if instance_id is set, grab this model object
    if instance_id:
        instance = model.objects.get(pk=instance_id)
        return model, instance_form, instance
    return model, instance_form


def _handle_cancel(request, instance=None):
    '''
    Handles clicks on the 'Cancel' button in forms. Returns a redirect to the
    last page, the user came from. If not given, to the detail-view of
    the object. Last fallback is a redirect to the common success page.
    '''
    if request.POST.get('_cancel', False):
        if request.GET.get('next', False):
            return HttpResponseRedirect(request.GET.get('next'))
        if instance and hasattr(instance, 'get_absolute_url'):
            return HttpResponseRedirect(instance.get_absolute_url())
        return HttpResponseRedirect(reverse('frontendadmin_success'))
    return None

def _handle_repsonse(request, instance=None):
    '''
    Handles redirects for completet form actions. Returns a redirect to the
    last page, the user came from. If not given, to the detail-view of
    the object. Last fallback is a redirect to the common success page.
    '''
    if request.GET.get('next', False):
        next = request.GET.get('next')
    elif instance and hasattr(instance, 'get_absolute_url'):
        next = instance.get_absolute_url()
    else:
        next = reverse('frontendadmin_success')
    return HttpResponseRedirect(next)

def _get_template(request, app_label=None, model_name=None):
    '''
    Returns wether the ajax or the normal (full html blown) template.
    '''
    template_name = request.is_ajax() and 'form_ajax.html' or 'form.html'
    if app_label is None and model_name is None:
        try:
            name = 'frontendadmin/%s_%s_%s' % (app_label, model_name, template_name)
            get_template(name)
            return name
        except TemplateDoesNotExist:
            pass
    return 'frontendadmin/%s' % template_name

@never_cache
@login_required
def add(request, app_label, model_name, mode_name='add',
                            form_fields=None,
                            form_exclude=None):

    # Get model, instance_form and instance for arguments
    instance_return = _get_instance(request, mode_name, app_label, model_name,
                                                                   form_fields=form_fields,
                                                                   form_exclude=form_exclude)
    if isinstance(instance_return, HttpResponseForbidden):
        return instance_return
    model, instance_form = instance_return

    # Handle cancel request
    cancel = _handle_cancel(request)
    if cancel:
        return cancel
    if request.method == 'POST':
        form = instance_form(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
            # Give the user a nice message
            request.user.message_set.create(
                message=ugettext(u'Your %(model_name)s was added successfully' % \
                    {'model_name': model._meta.verbose_name}))
            # Return to last page
            return _handle_repsonse(request, instance)
    else:<commit_msg>small fix for getting template name<commit_after># -*- coding: utf-8 -*-
from django.contrib.admin import site
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import get_model
from django.forms.models import modelform_factory
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.template.loader import get_template
from django.template import TemplateDoesNotExist
from django.utils.translation import ugettext
from django.views.decorators.cache import never_cache
from django.utils.importlib import import_module
from django.conf import settings
from django.forms import CharField

from forms import DeleteRequestForm, FrontendAdminModelForm


EXCLUDES = getattr(settings, 'FRONTEND_EXCLUDES', {})
FIELDS = getattr(settings, 'FRONTEND_FIELDS', {})
FORMS = getattr(settings, 'FRONTEND_FORMS', {})

def import_function(s):
    """
    Import a function given the string formatted as
    `module_name.function_name`  (eg `django.utils.text.capfirst`)
    """
    a = s.split('.')
    j = lambda x: '.'.join(x)
    return getattr(import_module(j(a[:-1])), a[-1])

def check_permission(request, mode_name, app_label, model_name):
    '''
    Check for proper permissions. mode_name may be either add, change or delete.
    '''
    p = '%s.%s_%s' % (app_label, mode_name, model_name)
    return request.user.is_active and request.user.has_perm(p)

def _get_instance(request, mode_name, app_label, model_name, instance_id=None,
                                            form=None,
                                            form_fields=None,
                                            form_exclude=None):
    '''
    Returns the model and an instance_form for the given arguments. If an primary
    key (instance_id) is given, it will return also the instance.

    If the user has no permission to add, change or delete the object, a
    HttpResponse is returned.
    '''
    # Check for permission to add/change/delete this object
    if not check_permission(request, mode_name, app_label, model_name):
        return HttpResponseForbidden('You have no permission to do this!')

    try:
        model = get_model(app_label, model_name)
    # Model does not exist
    except AttributeError:
        return HttpResponseForbidden('This model does not exist!')
    label = '%s.%s' % (app_label, model_name)
    # get form for model
    if label in FORMS and not form:
        form = import_function(FORMS[label])
    elif model in site._registry and not form:
        form = site._registry[model].form
    elif form is None:
        form = FrontendAdminModelForm
    
    if label in EXCLUDES:
        form_exclude = EXCLUDES[label]
    if label in FIELDS:
        form_fields = FIELDS[label]

    instance_form = modelform_factory(model, form=form,
                                      fields=form_fields, exclude=form_exclude)
    # if instance_id is set, grab this model object
    if instance_id:
        instance = model.objects.get(pk=instance_id)
        return model, instance_form, instance
    return model, instance_form


def _handle_cancel(request, instance=None):
    '''
    Handles clicks on the 'Cancel' button in forms. Returns a redirect to the
    last page, the user came from. If not given, to the detail-view of
    the object. Last fallback is a redirect to the common success page.
    '''
    if request.POST.get('_cancel', False):
        if request.GET.get('next', False):
            return HttpResponseRedirect(request.GET.get('next'))
        if instance and hasattr(instance, 'get_absolute_url'):
            return HttpResponseRedirect(instance.get_absolute_url())
        return HttpResponseRedirect(reverse('frontendadmin_success'))
    return None

def _handle_repsonse(request, instance=None):
    '''
    Handles redirects for completet form actions. Returns a redirect to the
    last page, the user came from. If not given, to the detail-view of
    the object. Last fallback is a redirect to the common success page.
    '''
    if request.GET.get('next', False):
        next = request.GET.get('next')
    elif instance and hasattr(instance, 'get_absolute_url'):
        next = instance.get_absolute_url()
    else:
        next = reverse('frontendadmin_success')
    return HttpResponseRedirect(next)

def _get_template(request, app_label=None, model_name=None):
    '''
    Returns wether the ajax or the normal (full html blown) template.
    '''
    template_name = request.is_ajax() and 'form_ajax.html' or 'form.html'
    if app_label is None and model_name is None:
        return 'frontendadmin/%s' % template_name
    
    try:
        name = 'frontendadmin/%s_%s_%s' % (app_label, model_name, template_name)
        get_template(name)
        return name
    except TemplateDoesNotExist:
        return 'frontendadmin/%s' % template_name

@never_cache
@login_required
def add(request, app_label, model_name, mode_name='add',
                            form_fields=None,
                            form_exclude=None):

    # Get model, instance_form and instance for arguments
    instance_return = _get_instance(request, mode_name, app_label, model_name,
                                                                   form_fields=form_fields,
                                                                   form_exclude=form_exclude)
    if isinstance(instance_return, HttpResponseForbidden):
        return instance_return
    model, instance_form = instance_return

    # Handle cancel request
    cancel = _handle_cancel(request)
    if cancel:
        return cancel
    if request.method == 'POST':
        form = instance_form(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
            # Give the user a nice message
            request.user.message_set.create(
                message=ugettext(u'Your %(model_name)s was added successfully' % \
                    {'model_name': model._meta.verbose_name}))
            # Return to last page
            return _handle_repsonse(request, instance)
    else:
{'fraction_non_alphanumeric': 0.08176608281540076, 'fraction_numerical': 0.00048430058923238354, 'mean_word_length': 2.7545454545454544, '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': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1166732', 'n_tokens_mistral': 3380, 'n_tokens_neox': 3338, 'n_words': 1030}