-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy path__init__.py
More file actions
169 lines (135 loc) · 5.4 KB
/
__init__.py
File metadata and controls
169 lines (135 loc) · 5.4 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
import re
from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
from django.db.models import AutoField, CharField
from feincms import settings
# ------------------------------------------------------------------------
def get_object(path, fail_silently=False):
# Return early if path isn't a string (might already be an callable or
# a class or whatever)
if not isinstance(path, str): # XXX bytes?
return path
try:
return import_module(path)
except ImportError:
try:
dot = path.rindex(".")
mod, fn = path[:dot], path[dot + 1 :]
return getattr(import_module(mod), fn)
except (AttributeError, ImportError):
if not fail_silently:
raise
# ------------------------------------------------------------------------
def get_model_instance(app_label, model_name, pk):
"""
Find an object instance given an app_label, a model name and the
object's pk.
This is used for page's get_link_target but can be used for other
content types that accept e.g. either an internal or external link.
"""
model = apps.get_model(app_label, model_name)
if not model:
return None
try:
instance = model._default_manager.get(pk=pk)
return instance
except model.DoesNotExist:
pass
return None
# ------------------------------------------------------------------------
REDIRECT_TO_RE = re.compile(r"^(?P<app_label>\w+).(?P<model_name>\w+):(?P<pk>\d+)$")
def match_model_string(s):
"""
Try to parse a string in format "app_label.model_name:pk", as is used
Page.get_link_target()
Returns a tuple app_label, model_name, pk or None if the string
does not match the expected format.
"""
match = REDIRECT_TO_RE.match(s)
if not match:
return None
matches = match.groupdict()
return (matches["app_label"], matches["model_name"], int(matches["pk"]))
# ------------------------------------------------------------------------
def copy_model_instance(obj, exclude=None):
"""
Copy a model instance, excluding primary key and optionally a list
of specified fields.
"""
exclude = exclude or ()
initial = {
f.name: getattr(obj, f.name)
for f in obj._meta.fields
if not isinstance(f, AutoField)
and f.name not in exclude
and f not in obj._meta.parents.values()
}
return obj.__class__(**initial)
# ------------------------------------------------------------------------
def shorten_string(str, max_length=50, ellipsis=" … "):
"""
Shorten a string for display, truncate it intelligently when too long.
Try to cut it in 2/3 + ellipsis + 1/3 of the original title. Also try to
cut the first part off at a white space boundary instead of in mid-word.
"""
if len(str) >= max_length:
first_part = int(max_length * 0.6)
next_space = str[first_part : (max_length // 2 - first_part)].find(" ")
if next_space >= 0 and first_part + next_space + len(ellipsis) < max_length:
first_part += next_space
return (
str[:first_part]
+ ellipsis
+ str[-(max_length - first_part - len(ellipsis)) :]
)
return str
# ------------------------------------------------------------------------
def get_singleton(template_key, cls=None, raise_exception=True):
cls = cls or settings.FEINCMS_DEFAULT_PAGE_MODEL
try:
model = apps.get_model(*cls.split("."))
if not model:
raise ImproperlyConfigured('Cannot load model "%s"' % cls)
try:
assert model._feincms_templates[template_key].singleton
except AttributeError as e:
raise ImproperlyConfigured(
f"{model!r} does not seem to be a valid FeinCMS base class ({e!r})"
)
except KeyError:
raise ImproperlyConfigured(
f"{template_key!r} is not a registered template for {model!r}!"
)
except AssertionError:
raise ImproperlyConfigured(
f"{template_key!r} is not a *singleton* template for {model!r}!"
)
try:
return model._default_manager.get(template_key=template_key)
except model.DoesNotExist:
raise # not yet created?
except model.MultipleObjectsReturned:
raise # hmm, not exactly a singleton...
except Exception:
if raise_exception:
raise
else:
return None
def get_singleton_url(template_key, cls=None, raise_exception=True):
obj = get_singleton(template_key, cls, raise_exception)
return obj.get_absolute_url() if obj else "#broken-link"
class ChoicesCharField(CharField):
"""
``models.CharField`` with choices, which makes the migration framework
always ignore changes to ``choices``, ever.
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault("choices", [("", "")]) # Non-empty choices for get_*_display
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs["choices"] = [("", "")]
return name, "django.db.models.CharField", args, kwargs