Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
54 lines (42 loc) · 1.64 KB
/
Copy pathcommon.py
File metadata and controls
54 lines (42 loc) · 1.64 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
# ------- Creating new class of array field using postgres.fields -------
from django import forms
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.contrib import messages
class ChoiceArrayField(ArrayField):
"""
A field that allows us to store an array of choices.
Uses Django 1.9's postgres ArrayField
and a MultipleChoiceField for its formfield.
Usage:
choices = ChoiceArrayField(models.CharField(max_length=...,
choices=(...,)),
default=[...])
"""
def formfield(self, **kwargs):
defaults = {
"form_class": forms.MultipleChoiceField,
"choices": self.base_field.choices,
"widget": forms.CheckboxSelectMultiple, # remove this for list selection
}
defaults.update(kwargs)
return super(ArrayField, self).formfield(**defaults)
# ----------------------------------------------------------------------
def retrieve_none_or_403(
request, target_model, identifier, message="You are not allowed to edit this."
):
try:
instance = target_model.objects.get(id=identifier)
if instance.user != request.user:
messages.warning(request, message)
raise PermissionDenied
except ObjectDoesNotExist:
instance = None
return instance
def db_retrieve_or_none(target_model, identifier):
qs = target_model.objects.filter(id=identifier)
if qs.exists():
instance = qs.first()
else:
instance = None
return instance