~grupoesoc/cubicerp-addons/7.0

« back to all changes in this revision

Viewing changes to report_geraldo/lib/geraldo/site/newsite/django_1_0/django/shortcuts/__init__.py

  • Committer: Cubic ERP
  • Date: 2014-01-07 15:38:09 UTC
  • Revision ID: info@cubicerp.com-20140107153809-4jmif3zoi8rcveve
[ADD] cubicReport

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
This module collects helper functions and classes that "span" multiple levels
 
3
of MVC. In other words, these functions/classes introduce controlled coupling
 
4
for convenience's sake.
 
5
"""
 
6
 
 
7
from django.template import loader
 
8
from django.http import HttpResponse, Http404
 
9
from django.db.models.manager import Manager
 
10
from django.db.models.query import QuerySet
 
11
 
 
12
def render_to_response(*args, **kwargs):
 
13
    """
 
14
    Returns a HttpResponse whose content is filled with the result of calling
 
15
    django.template.loader.render_to_string() with the passed arguments.
 
16
    """
 
17
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
 
18
    return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
 
19
 
 
20
def _get_queryset(klass):
 
21
    """
 
22
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
 
23
    get_object_or_404 and get_list_or_404 more DRY.
 
24
    """
 
25
    if isinstance(klass, QuerySet):
 
26
        return klass
 
27
    elif isinstance(klass, Manager):
 
28
        manager = klass
 
29
    else:
 
30
        manager = klass._default_manager
 
31
    return manager.all()
 
32
 
 
33
def get_object_or_404(klass, *args, **kwargs):
 
34
    """
 
35
    Uses get() to return an object, or raises a Http404 exception if the object
 
36
    does not exist.
 
37
 
 
38
    klass may be a Model, Manager, or QuerySet object. All other passed
 
39
    arguments and keyword arguments are used in the get() query.
 
40
 
 
41
    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
 
42
    object is found.
 
43
    """
 
44
    queryset = _get_queryset(klass)
 
45
    try:
 
46
        return queryset.get(*args, **kwargs)
 
47
    except queryset.model.DoesNotExist:
 
48
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
 
49
 
 
50
def get_list_or_404(klass, *args, **kwargs):
 
51
    """
 
52
    Uses filter() to return a list of objects, or raise a Http404 exception if
 
53
    the list is empty.
 
54
 
 
55
    klass may be a Model, Manager, or QuerySet object. All other passed
 
56
    arguments and keyword arguments are used in the filter() query.
 
57
    """
 
58
    queryset = _get_queryset(klass)
 
59
    obj_list = list(queryset.filter(*args, **kwargs))
 
60
    if not obj_list:
 
61
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
 
62
    return obj_list