<commit_before>from django import models
from django.core.xheaders import populate_xheaders
from django.core.template import loader
from django.core import formfields, meta
from django.views.auth.login import redirect_to_login
from django.core.extensions import DjangoContext
from django.core.paginator import ObjectPaginator, InvalidPage
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured

def create_object(request, app_label, module_name, template_name=None,
        template_loader=loader, extra_context={}, post_save_redirect=None,
        login_required=False, follow=None, context_processors=None):
    """
    Generic object-creation function.

    Templates: ``<app_label>/<module_name>_form``
    Context:
        form
            the form wrapper for the object
    """
    if login_required and request.user.is_anonymous():
        return redirect_to_login(request.path)

    mod = models.get_module(app_label, module_name)
    manipulator = mod.AddManipulator(follow=follow)
    if request.POST:
        # If data was POSTed, we're trying to create a new object
        new_data = request.POST.copy()

        if mod.Klass._meta.has_field_type(meta.FileField):
            new_data.update(request.FILES)

        # Check for errors
        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)

        if not errors:
            # No errors -- this means we can save the data!
            new_object = manipulator.save(new_data)

            if not request.user.is_anonymous():
                request.user.add_message("The %s was created sucessfully." % mod.Klass._meta.verbose_name)

            # Redirect to the new object: first by trying post_save_redirect,
            # then by obj.get_absolute_url; fail if neither works.
            if post_save_redirect:
                return HttpResponseRedirect(post_save_redirect % new_object.__dict__)
            elif hasattr(new_object, 'get_absolute_url'):
                return HttpResponseRedirect(new_object.get_absolute_url())
            else:
                raise ImproperlyConfigured("No URL to redirect to from generic create view.")
    else:
        # No POST, so we want a brand new form without any data or errors
        errors = {}
        new_data = manipulator.flatten_data()

    # Create the FormWrapper, template, context, response
    form = formfields.FormWrapper(manipulator, new_data, errors)
    if not template_name:
        template_name = "%s/%s_form" % (app_label, module_name)
    t = template_loader.get_template(template_name)
    c = DjangoContext(request, {
        'form': form,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    return HttpResponse(t.render(c))

def update_object(request, app_label, module_name, object_id=None, slug=None,
        slug_field=None, template_name=None, template_loader=loader,
        extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
        login_required=False, follow=None, context_processors=None,
        template_object_name='object'):
    """
    Generic object-update function.

    Templates: ``<app_label>/<module_name>_form``
    Context:
        form
            the form wrapper for the object
        object
            the original object being edited
    """
    if login_required and request.user.is_anonymous():
        return redirect_to_login(request.path)

    mod = models.get_module(app_label, module_name)

    # Look up the object to be edited
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
    elif slug and slug_field:
        lookup_kwargs['%s__exact' % slug_field] = slug
    else:
        raise AttributeError("Generic edit view must be called with either an object_id or a slug/slug_field")
    lookup_kwargs.update(extra_lookup_kwargs)
    try:
        object = mod.get_object(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))

    manipulator = mod.ChangeManipulator(object.id, follow=follow)

    if request.POST:
        new_data = request.POST.copy()
        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)
        if not errors:
            manipulator.save(new_data)

            if not request.user.is_anonymous():
                request.user.add_message("The %s was updated sucessfully." % mod.Klass._meta.verbose_name)

            # Do a post-after-redirect so that reload works, etc.
            if post_save_redirect:
                return HttpResponseRedirect(post_save_redirect % object.__dict__)
            elif hasattr(object, 'get_absolute_url'):
                return HttpResponseRedirect(object.get_absolute_url())
            else:
                raise ImproperlyConfigured("No URL to redirect to from generic create view.")
    else:
        errors = {}
        # This makes sure the form acurate represents the fields of the place.
        new_data = manipulator.flatten_data()

    form = formfields.FormWrapper(manipulator, new_data, errors)
    if not template_name:
        template_name = "%s/%s_form" % (app_label, module_name)
    t = template_loader.get_template(template_name)
    c = DjangoContext(request, {
        'form': form,
        template_object_name: object,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value<commit_msg>Fixed #1557 in trunk<commit_after>from django import models
from django.core.xheaders import populate_xheaders
from django.core.template import loader
from django.core import formfields, meta
from django.views.auth.login import redirect_to_login
from django.core.extensions import DjangoContext
from django.core.paginator import ObjectPaginator, InvalidPage
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured

def create_object(request, app_label, module_name, template_name=None,
        template_loader=loader, extra_context={}, post_save_redirect=None,
        login_required=False, follow=None, context_processors=None):
    """
    Generic object-creation function.

    Templates: ``<app_label>/<module_name>_form``
    Context:
        form
            the form wrapper for the object
    """
    if login_required and request.user.is_anonymous():
        return redirect_to_login(request.path)

    mod = models.get_module(app_label, module_name)
    manipulator = mod.AddManipulator(follow=follow)
    if request.POST:
        # If data was POSTed, we're trying to create a new object
        new_data = request.POST.copy()

        if mod.Klass._meta.has_field_type(meta.FileField):
            new_data.update(request.FILES)

        # Check for errors
        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)

        if not errors:
            # No errors -- this means we can save the data!
            new_object = manipulator.save(new_data)

            if not request.user.is_anonymous():
                request.user.add_message("The %s was created successfully." % mod.Klass._meta.verbose_name)

            # Redirect to the new object: first by trying post_save_redirect,
            # then by obj.get_absolute_url; fail if neither works.
            if post_save_redirect:
                return HttpResponseRedirect(post_save_redirect % new_object.__dict__)
            elif hasattr(new_object, 'get_absolute_url'):
                return HttpResponseRedirect(new_object.get_absolute_url())
            else:
                raise ImproperlyConfigured("No URL to redirect to from generic create view.")
    else:
        # No POST, so we want a brand new form without any data or errors
        errors = {}
        new_data = manipulator.flatten_data()

    # Create the FormWrapper, template, context, response
    form = formfields.FormWrapper(manipulator, new_data, errors)
    if not template_name:
        template_name = "%s/%s_form" % (app_label, module_name)
    t = template_loader.get_template(template_name)
    c = DjangoContext(request, {
        'form': form,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    return HttpResponse(t.render(c))

def update_object(request, app_label, module_name, object_id=None, slug=None,
        slug_field=None, template_name=None, template_loader=loader,
        extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
        login_required=False, follow=None, context_processors=None,
        template_object_name='object'):
    """
    Generic object-update function.

    Templates: ``<app_label>/<module_name>_form``
    Context:
        form
            the form wrapper for the object
        object
            the original object being edited
    """
    if login_required and request.user.is_anonymous():
        return redirect_to_login(request.path)

    mod = models.get_module(app_label, module_name)

    # Look up the object to be edited
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
    elif slug and slug_field:
        lookup_kwargs['%s__exact' % slug_field] = slug
    else:
        raise AttributeError("Generic edit view must be called with either an object_id or a slug/slug_field")
    lookup_kwargs.update(extra_lookup_kwargs)
    try:
        object = mod.get_object(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))

    manipulator = mod.ChangeManipulator(object.id, follow=follow)

    if request.POST:
        new_data = request.POST.copy()
        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)
        if not errors:
            manipulator.save(new_data)

            if not request.user.is_anonymous():
                request.user.add_message("The %s was updated successfully." % mod.Klass._meta.verbose_name)

            # Do a post-after-redirect so that reload works, etc.
            if post_save_redirect:
                return HttpResponseRedirect(post_save_redirect % object.__dict__)
            elif hasattr(object, 'get_absolute_url'):
                return HttpResponseRedirect(object.get_absolute_url())
            else:
                raise ImproperlyConfigured("No URL to redirect to from generic create view.")
    else:
        errors = {}
        # This makes sure the form acurate represents the fields of the place.
        new_data = manipulator.flatten_data()

    form = formfields.FormWrapper(manipulator, new_data, errors)
    if not template_name:
        template_name = "%s/%s_form" % (app_label, module_name)
    t = template_loader.get_template(template_name)
    c = DjangoContext(request, {
        'form': form,
        template_object_name: object,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
{'fraction_non_alphanumeric': 0.08425162689804772, 'fraction_numerical': 0.0017353579175704988, 'mean_word_length': 2.8781965006729475, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, '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': '7643405', 'n_tokens_mistral': 3302, 'n_tokens_neox': 3217, 'n_words': 824}