Ticket #1085: generic.diff

File generic.diff, 22.4 KB (added by Esaj, 19 years ago)

Use 'model' arg instead of 'module_name' for generic views

  • django/core/xheaders.py

     
    44
    55This module contains utility functions for retrieving and doing interesting
    66things with these special "X-Headers" (so called because the HTTP spec demands
    7 that custom headers are prefxed with "X-").
     7that custom headers are prefixed with "X-").
    88
    99Next time you're at slashdot.org, watch out for X-Fry and X-Bender. :)
    1010"""
    1111
    12 def populate_xheaders(request, response, package, python_module_name, object_id):
     12def populate_xheaders(request, response, object_type, object_id):
    1313    """
    1414    Adds the "X-Object-Type" and "X-Object-Id" headers to the given
    15     HttpResponse according to the given package, python_module_name and
     15    HttpResponse according to the given object_type and
    1616    object_id -- but only if the given HttpRequest object has an IP address
    1717    within the INTERNAL_IPS setting.
    1818    """
    1919    from django.conf.settings import INTERNAL_IPS
    2020    if request.META.get('REMOTE_ADDR') in INTERNAL_IPS:
    21         response['X-Object-Type'] = "%s.%s" % (package, python_module_name)
     21        response['X-Object-Type'] = str(object_type)
    2222        response['X-Object-Id'] = str(object_id)
  • django/views/generic/date_based.py

     
    22from django.core.exceptions import Http404, ObjectDoesNotExist
    33from django.core.extensions import DjangoContext
    44from django.core.xheaders import populate_xheaders
    5 from django.models import get_module
    65from django.utils.httpwrappers import HttpResponse
     6from string import lower
    77import datetime, time
    88
    9 def archive_index(request, app_label, module_name, date_field, num_latest=15,
     9def archive_index(request, app_label, model, date_field, num_latest=15,
    1010        template_name=None, template_loader=loader, extra_lookup_kwargs={},
    1111        extra_context={}, allow_empty=False, context_processors=None):
    1212    """
    1313    Generic top-level archive of date-based objects.
    1414
    15     Templates: ``<app_label>/<module_name>_archive``
     15    Templates: ``<app_label>/<model_name>_archive``
    1616    Context:
    1717        date_list
    1818            List of years
    1919        latest
    2020            Latest N (defaults to 15) objects by date
    2121    """
    22     mod = get_module(app_label, module_name)
    2322    lookup_kwargs = {'%s__lte' % date_field: datetime.datetime.now()}
    2423    lookup_kwargs.update(extra_lookup_kwargs)
    25     date_list = getattr(mod, "get_%s_list" % date_field)('year', **lookup_kwargs)[::-1]
     24    date_list = getattr(model.objects, "get_%s_list" % date_field)('year', **lookup_kwargs)[::-1]
    2625    if not date_list and not allow_empty:
    27         raise Http404("No %s.%s available" % (app_label, module_name))
     26        raise Http404("No %s available" % model.__name__)
    2827
    2928    if date_list and num_latest:
    3029        lookup_kwargs.update({
    3130            'limit': num_latest,
    3231            'order_by': ('-' + date_field,),
    3332        })
    34         latest = mod.get_list(**lookup_kwargs)
     33        latest = model.objects.get_list(**lookup_kwargs)
    3534    else:
    3635        latest = None
    3736
    3837    if not template_name:
    39         template_name = "%s/%s_archive" % (app_label, module_name)
     38        template_name = "%s/%s_archive" % (app_label, lower(model.__name__))
    4039    t = template_loader.get_template(template_name)
    4140    c = DjangoContext(request, {
    4241        'date_list' : date_list,
     
    4948            c[key] = value
    5049    return HttpResponse(t.render(c))
    5150
    52 def archive_year(request, year, app_label, module_name, date_field,
     51def archive_year(request, year, app_label, model, date_field,
    5352        template_name=None, template_loader=loader, extra_lookup_kwargs={},
    5453        extra_context={}, context_processors=None):
    5554    """
    5655    Generic yearly archive view.
    5756
    58     Templates: ``<app_label>/<module_name>_archive_year``
     57    Templates: ``<app_label>/<model_name>_archive_year``
    5958    Context:
    6059        date_list
    6160            List of months in this year with objects
    6261        year
    6362            This year
    6463    """
    65     mod = get_module(app_label, module_name)
    6664    now = datetime.datetime.now()
    6765    lookup_kwargs = {'%s__year' % date_field: year}
    6866    # Only bother to check current date if the year isn't in the past.
    6967    if int(year) >= now.year:
    7068        lookup_kwargs['%s__lte' % date_field] = now
    7169    lookup_kwargs.update(extra_lookup_kwargs)
    72     date_list = getattr(mod, "get_%s_list" % date_field)('month', **lookup_kwargs)
     70    date_list = getattr(model.objects, "get_%s_list" % date_field)('month', **lookup_kwargs)
    7371    if not date_list:
    7472        raise Http404
    7573    if not template_name:
    76         template_name = "%s/%s_archive_year" % (app_label, module_name)
     74        template_name = "%s/%s_archive_year" % (app_label, lower(model.__name__))
    7775    t = template_loader.get_template(template_name)
    7876    c = DjangoContext(request, {
    7977        'date_list': date_list,
     
    8684            c[key] = value
    8785    return HttpResponse(t.render(c))
    8886
    89 def archive_month(request, year, month, app_label, module_name, date_field,
     87def archive_month(request, year, month, app_label, model, date_field,
    9088        month_format='%b', template_name=None, template_loader=loader,
    9189        extra_lookup_kwargs={}, extra_context={}, context_processors=None):
    9290    """
    9391    Generic monthly archive view.
    9492
    95     Templates: ``<app_label>/<module_name>_archive_month``
     93    Templates: ``<app_label>/<model_name>_archive_month``
    9694    Context:
    9795        month:
    9896            this month
     
    104102    except ValueError:
    105103        raise Http404
    106104
    107     mod = get_module(app_label, module_name)
    108105    now = datetime.datetime.now()
    109106    # Calculate first and last day of month, for use in a date-range lookup.
    110107    first_day = date.replace(day=1)
     
    117114    if last_day >= now.date():
    118115        lookup_kwargs['%s__lte' % date_field] = now
    119116    lookup_kwargs.update(extra_lookup_kwargs)
    120     object_list = mod.get_list(**lookup_kwargs)
     117    object_list = model.objects.get_list(**lookup_kwargs)
    121118    if not object_list:
    122119        raise Http404
    123120    if not template_name:
    124         template_name = "%s/%s_archive_month" % (app_label, module_name)
     121        template_name = "%s/%s_archive_month" % (app_label, lower(model.__name__))
    125122    t = template_loader.get_template(template_name)
    126123    c = DjangoContext(request, {
    127124        'object_list': object_list,
     
    134131            c[key] = value
    135132    return HttpResponse(t.render(c))
    136133
    137 def archive_day(request, year, month, day, app_label, module_name, date_field,
     134def archive_day(request, year, month, day, app_label, model, date_field,
    138135        month_format='%b', day_format='%d', template_name=None,
    139136        template_loader=loader, extra_lookup_kwargs={}, extra_context={},
    140137        allow_empty=False, context_processors=None):
    141138    """
    142139    Generic daily archive view.
    143140
    144     Templates: ``<app_label>/<module_name>_archive_day``
     141    Templates: ``<app_label>/<model_name>_archive_day``
    145142    Context:
    146143        object_list:
    147144            list of objects published that day
     
    157154    except ValueError:
    158155        raise Http404
    159156
    160     mod = get_module(app_label, module_name)
    161157    now = datetime.datetime.now()
    162158    lookup_kwargs = {
    163159        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
     
    166162    if date >= now.date():
    167163        lookup_kwargs['%s__lte' % date_field] = now
    168164    lookup_kwargs.update(extra_lookup_kwargs)
    169     object_list = mod.get_list(**lookup_kwargs)
     165    object_list = model.objects.get_list(**lookup_kwargs)
    170166    if not allow_empty and not object_list:
    171167        raise Http404
    172168    if not template_name:
    173         template_name = "%s/%s_archive_day" % (app_label, module_name)
     169        template_name = "%s/%s_archive_day" % (app_label, lower(model.__name__))
    174170    t = template_loader.get_template(template_name)
    175171    c = DjangoContext(request, {
    176172        'object_list': object_list,
     
    197193    })
    198194    return archive_day(request, **kwargs)
    199195
    200 def object_detail(request, year, month, day, app_label, module_name, date_field,
     196def object_detail(request, year, month, day, app_label, model, date_field,
    201197        month_format='%b', day_format='%d', object_id=None, slug=None,
    202198        slug_field=None, template_name=None, template_name_field=None,
    203199        template_loader=loader, extra_lookup_kwargs={}, extra_context={},
     
    205201    """
    206202    Generic detail view from year/month/day/slug or year/month/day/id structure.
    207203
    208     Templates: ``<app_label>/<module_name>_detail``
     204    Templates: ``<app_label>/<model_name>_detail``
    209205    Context:
    210206        object:
    211207            the object to be detailed
     
    215211    except ValueError:
    216212        raise Http404
    217213
    218     mod = get_module(app_label, module_name)
    219214    now = datetime.datetime.now()
    220215    lookup_kwargs = {
    221216        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
     
    224219    if date >= now.date():
    225220        lookup_kwargs['%s__lte' % date_field] = now
    226221    if object_id:
    227         lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
     222        lookup_kwargs['%s__exact' % model.Klass._meta.pk.name] = object_id
    228223    elif slug and slug_field:
    229224        lookup_kwargs['%s__exact' % slug_field] = slug
    230225    else:
    231226        raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield")
    232227    lookup_kwargs.update(extra_lookup_kwargs)
    233228    try:
    234         object = mod.get_object(**lookup_kwargs)
     229        object = model.objects.get_object(**lookup_kwargs)
    235230    except ObjectDoesNotExist:
    236         raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
     231        raise Http404("%s does not exist for %s" % (model.__name__, lookup_kwargs))
    237232    if not template_name:
    238         template_name = "%s/%s_detail" % (app_label, module_name)
     233        template_name = "%s/%s_detail" % (app_label, lower(model.__name__))
    239234    if template_name_field:
    240235        template_name_list = [getattr(object, template_name_field), template_name]
    241236        t = template_loader.select_template(template_name_list)
     
    250245        else:
    251246            c[key] = value
    252247    response = HttpResponse(t.render(c))
    253     populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
     248    populate_xheaders(request, response, model.__name__, getattr(object, object._meta.pk.name))
    254249    return response
  • django/views/generic/list_detail.py

     
    55from django.core.extensions import DjangoContext
    66from django.core.paginator import ObjectPaginator, InvalidPage
    77from django.core.exceptions import Http404, ObjectDoesNotExist
     8from string import lower
    89
    9 def object_list(request, app_label, module_name, paginate_by=None, allow_empty=False,
     10def object_list(request, app_label, model, paginate_by=None, allow_empty=False,
    1011        template_name=None, template_loader=loader, extra_lookup_kwargs={},
    1112        extra_context={}, context_processors=None):
    1213    """
    1314    Generic list of objects.
    1415
    15     Templates: ``<app_label>/<module_name>_list``
     16    Templates: ``<app_label>/<model_name>_list``
    1617    Context:
    1718        object_list
    1819            list of objects
     
    3536        hits
    3637            number of objects, total
    3738    """
    38     mod = models.get_module(app_label, module_name)
    3939    lookup_kwargs = extra_lookup_kwargs.copy()
    4040    if paginate_by:
    41         paginator = ObjectPaginator(mod, lookup_kwargs, paginate_by)
     41        paginator = ObjectPaginator(model, lookup_kwargs, paginate_by)
    4242        page = request.GET.get('page', 0)
    4343        try:
    4444            object_list = paginator.get_page(page)
     
    6161            'hits' : paginator.hits,
    6262        }, context_processors)
    6363    else:
    64         object_list = mod.get_list(**lookup_kwargs)
     64        object_list = model.objects.get_list(**lookup_kwargs)
    6565        c = DjangoContext(request, {
    6666            'object_list': object_list,
    6767            'is_paginated': False
     
    7474        else:
    7575            c[key] = value
    7676    if not template_name:
    77         template_name = "%s/%s_list" % (app_label, module_name)
     77        template_name = "%s/%s_list" % (app_label, lower(model.__name__))
    7878    t = template_loader.get_template(template_name)
    7979    return HttpResponse(t.render(c))
    8080
    81 def object_detail(request, app_label, module_name, object_id=None, slug=None,
     81def object_detail(request, app_label, model, object_id=None, slug=None,
    8282        slug_field=None, template_name=None, template_name_field=None,
    8383        template_loader=loader, extra_lookup_kwargs={}, extra_context={},
    8484        context_processors=None):
    8585    """
    8686    Generic list of objects.
    8787
    88     Templates: ``<app_label>/<module_name>_detail``
     88    Templates: ``<app_label>/<model_name>_detail``
    8989    Context:
    9090        object
    9191            the object
    9292    """
    93     mod = models.get_module(app_label, module_name)
    9493    lookup_kwargs = {}
    9594    if object_id:
    9695        lookup_kwargs['pk'] = object_id
     
    10099        raise AttributeError("Generic detail view must be called with either an object_id or a slug/slug_field")
    101100    lookup_kwargs.update(extra_lookup_kwargs)
    102101    try:
    103         object = mod.get_object(**lookup_kwargs)
     102        object = model.objects.get_object(**lookup_kwargs)
    104103    except ObjectDoesNotExist:
    105         raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
     104        raise Http404("%s does not exist for %s" % (model.__name__, lookup_kwargs))
    106105    if not template_name:
    107         template_name = "%s/%s_detail" % (app_label, module_name)
     106        template_name = "%s/%s_detail" % (app_label, lower(model.__name__))
    108107    if template_name_field:
    109108        template_name_list = [getattr(object, template_name_field), template_name]
    110109        t = template_loader.select_template(template_name_list)
     
    119118        else:
    120119            c[key] = value
    121120    response = HttpResponse(t.render(c))
    122     populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
     121    populate_xheaders(request, response, model.__name__, getattr(object, object._meta.pk.name))
    123122    return response
  • django/views/generic/create_update.py

     
    77from django.core.paginator import ObjectPaginator, InvalidPage
    88from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
    99from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured
     10from string import lower
    1011
    11 def create_object(request, app_label, module_name, template_name=None,
     12def create_object(request, app_label, model, template_name=None,
    1213        template_loader=loader, extra_context={}, post_save_redirect=None,
    1314        login_required=False, follow=None, context_processors=None):
    1415    """
    1516    Generic object-creation function.
    1617
    17     Templates: ``<app_label>/<module_name>_form``
     18    Templates: ``<app_label>/<model_name>_form``
    1819    Context:
    1920        form
    2021            the form wrapper for the object
     
    2223    if login_required and request.user.is_anonymous():
    2324        return redirect_to_login(request.path)
    2425
    25     mod = models.get_module(app_label, module_name)
    2626    manipulator = mod.AddManipulator(follow=follow)
    2727    if request.POST:
    2828        # If data was POSTed, we're trying to create a new object
    2929        new_data = request.POST.copy()
    3030
    31         if mod.Klass._meta.has_field_type(meta.FileField):
     31        if model.Klass._meta.has_field_type(meta.FileField):
    3232            new_data.update(request.FILES)
    3333
    3434        # Check for errors
     
    4040            new_object = manipulator.save(new_data)
    4141
    4242            if not request.user.is_anonymous():
    43                 request.user.add_message("The %s was created sucessfully." % mod.Klass._meta.verbose_name)
     43                request.user.add_message("The %s was created sucessfully." % model.Klass._meta.verbose_name)
    4444
    4545            # Redirect to the new object: first by trying post_save_redirect,
    4646            # then by obj.get_absolute_url; fail if neither works.
     
    5858    # Create the FormWrapper, template, context, response
    5959    form = formfields.FormWrapper(manipulator, new_data, errors)
    6060    if not template_name:
    61         template_name = "%s/%s_form" % (app_label, module_name)
     61        template_name = "%s/%s_form" % (app_label, lower(model.__name__))
    6262    t = template_loader.get_template(template_name)
    6363    c = DjangoContext(request, {
    6464        'form': form,
     
    7070            c[key] = value
    7171    return HttpResponse(t.render(c))
    7272
    73 def update_object(request, app_label, module_name, object_id=None, slug=None,
     73def update_object(request, app_label, model, object_id=None, slug=None,
    7474        slug_field=None, template_name=None, template_loader=loader,
    7575        extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
    7676        login_required=False, follow=None, context_processors=None):
    7777    """
    7878    Generic object-update function.
    7979
    80     Templates: ``<app_label>/<module_name>_form``
     80    Templates: ``<app_label>/<model>_form``
    8181    Context:
    8282        form
    8383            the form wrapper for the object
     
    8787    if login_required and request.user.is_anonymous():
    8888        return redirect_to_login(request.path)
    8989
    90     mod = models.get_module(app_label, module_name)
    9190
    9291    # Look up the object to be edited
    9392    lookup_kwargs = {}
    9493    if object_id:
    95         lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
     94        lookup_kwargs['%s__exact' % model.Klass._meta.pk.name] = object_id
    9695    elif slug and slug_field:
    9796        lookup_kwargs['%s__exact' % slug_field] = slug
    9897    else:
    9998        raise AttributeError("Generic edit view must be called with either an object_id or a slug/slug_field")
    10099    lookup_kwargs.update(extra_lookup_kwargs)
    101100    try:
    102         object = mod.get_object(**lookup_kwargs)
     101        object = model.objects.get_object(**lookup_kwargs)
    103102    except ObjectDoesNotExist:
    104         raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
     103        raise Http404("%s does not exist for %s" % (model.__name__, lookup_kwargs))
    105104
    106     manipulator = mod.ChangeManipulator(object.id, follow=follow)
     105    manipulator = model.ChangeManipulator(object.id, follow=follow)
    107106
    108107    if request.POST:
    109108        new_data = request.POST.copy()
     
    113112            manipulator.save(new_data)
    114113
    115114            if not request.user.is_anonymous():
    116                 request.user.add_message("The %s was updated sucessfully." % mod.Klass._meta.verbose_name)
     115                request.user.add_message("The %s was updated sucessfully." % model.Klass._meta.verbose_name)
    117116
    118117            # Do a post-after-redirect so that reload works, etc.
    119118            if post_save_redirect:
     
    129128
    130129    form = formfields.FormWrapper(manipulator, new_data, errors)
    131130    if not template_name:
    132         template_name = "%s/%s_form" % (app_label, module_name)
     131        template_name = "%s/%s_form" % (app_label, lower(model.__name__))
    133132    t = template_loader.get_template(template_name)
    134133    c = DjangoContext(request, {
    135134        'form': form,
     
    141140        else:
    142141            c[key] = value
    143142    response = HttpResponse(t.render(c))
    144     populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
     143    populate_xheaders(request, response, model.__name__, getattr(object, object._meta.pk.name))
    145144    return response
    146145
    147 def delete_object(request, app_label, module_name, post_delete_redirect,
     146def delete_object(request, app_label, model, post_delete_redirect,
    148147        object_id=None, slug=None, slug_field=None, template_name=None,
    149148        template_loader=loader, extra_lookup_kwargs={}, extra_context={},
    150149        login_required=False, context_processors=None):
     
    155154    fetched using GET; for safty, deletion will only be performed if this
    156155    view is POSTed.
    157156
    158     Templates: ``<app_label>/<module_name>_confirm_delete``
     157    Templates: ``<app_label>/<model_name>_confirm_delete``
    159158    Context:
    160159        object
    161160            the original object being deleted
     
    163162    if login_required and request.user.is_anonymous():
    164163        return redirect_to_login(request.path)
    165164
    166     mod = models.get_module(app_label, module_name)
    167165
    168166    # Look up the object to be edited
    169167    lookup_kwargs = {}
    170168    if object_id:
    171         lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
     169        lookup_kwargs['%s__exact' % model.Klass._meta.pk.name] = object_id
    172170    elif slug and slug_field:
    173171        lookup_kwargs['%s__exact' % slug_field] = slug
    174172    else:
    175173        raise AttributeError("Generic delete view must be called with either an object_id or a slug/slug_field")
    176174    lookup_kwargs.update(extra_lookup_kwargs)
    177175    try:
    178         object = mod.get_object(**lookup_kwargs)
     176        object = model.objects.get_object(**lookup_kwargs)
    179177    except ObjectDoesNotExist:
    180         raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
     178        raise Http404("%s does not exist for %s" % (model.__name__, lookup_kwargs))
    181179
    182180    if request.META['REQUEST_METHOD'] == 'POST':
    183181        object.delete()
    184182        if not request.user.is_anonymous():
    185             request.user.add_message("The %s was deleted." % mod.Klass._meta.verbose_name)
     183            request.user.add_message("The %s was deleted." % model.Klass._meta.verbose_name)
    186184        return HttpResponseRedirect(post_delete_redirect)
    187185    else:
    188186        if not template_name:
    189             template_name = "%s/%s_confirm_delete" % (app_label, module_name)
     187            template_name = "%s/%s_confirm_delete" % (app_label, lower(model.__name__))
    190188        t = template_loader.get_template(template_name)
    191189        c = DjangoContext(request, {
    192190            'object': object,
     
    197195            else:
    198196                c[key] = value
    199197        response = HttpResponse(t.render(c))
    200         populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
     198        populate_xheaders(request, response, model.__name__, getattr(object, object._meta.pk.name))
    201199        return response
Back to Top