-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathshortcuts.py
More file actions
94 lines (73 loc) · 2.58 KB
/
Copy pathshortcuts.py
File metadata and controls
94 lines (73 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from django.core.paginator import Paginator
from django.template.response import TemplateResponse
__all__ = ("render_detail", "render_list", "template_name")
def template_name(model, template_name_suffix):
"""
Given a model and a template name suffix, return the resulting template
path::
>>> template_name(Article, "_detail")
"articles/article_detail.html"
>>> template_name(User, "_form")
"auth/user_form.html"
"""
return (
f"{model._meta.app_label}/{model._meta.model_name}{template_name_suffix}.html"
)
def render_list(
request,
queryset,
context=None,
*,
model=None,
paginate_by=None,
template_name_suffix="_list",
):
"""
Render a list of items
Usage example::
def article_list(request, ...):
queryset = Article.objects.published()
return render_list(
request,
queryset,
paginate_by=10,
)
You can also pass an additional context dictionary and/or specify the
template name suffix. The query parameter ``page`` is hardcoded for
specifying the current page if using pagination.
The queryset (or the page if using pagination) are passed into the template
as ``object_list`` AND ``<model_name>_list``, i.e. ``article_list`` in the
example above.
"""
context = context or {}
if paginate_by:
object_list = Paginator(queryset, paginate_by).get_page(request.GET.get("page"))
else:
object_list = queryset
model = model or queryset.model
context.update(
{"object_list": object_list, "%s_list" % model._meta.model_name: object_list}
)
return TemplateResponse(
request, template_name(model, template_name_suffix), context
)
def render_detail(request, object, context=None, *, template_name_suffix="_detail"):
"""
Render a single item
Usage example::
def article_detail(request, slug):
article = get_object_or_404(Article.objects.published(), slug=slug)
return render_detail(
request,
article,
)
An additional context dictionary is also supported, and specifying the
template name suffix too.
The ``Article`` instance in the example above is passed as ``object``
AND ``article`` (lowercased model name) into the template.
"""
context = context or {}
context.update({"object": object, object._meta.model_name: object})
return TemplateResponse(
request, template_name(object, template_name_suffix), context
)