Newer
Older
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
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.forms import ModelForm, ChoiceField
from django.utils.translation import ugettext_lazy as _
class HighlightedContentItemForm(ModelForm):
item = ChoiceField(label=_('item'), choices=[], required=False)
def __init__(self, *args, **kwargs):
super(HighlightedContentItemForm, self).__init__(*args, **kwargs)
self.fields['item'] = self.get_item_field()
def get_item_field(self):
models = [(ct.pk, ct.model_class()) for ct in self.get_content_types_queryset()]
choices = []
for content_type_id, model in models:
choices.append([
model._meta.verbose_name.title(),
[('%d:%s' % (content_type_id, o.pk), '%s' % o) for o in model.objects.all()]
])
choices.sort(key=lambda x: x[0])
choices.insert(0, ('', _('None')))
field = ChoiceField(label=_('item'), choices=choices, required=False)
current_item_type_id = getattr(self.instance, 'content_type_id', None)
current_object_id = getattr(self.instance, 'object_id', None)
if current_item_type_id and current_object_id:
field.initial = '%d:%s' % (current_item_type_id, current_object_id)
return field
def get_item(self):
data = self.cleaned_data
if not data['item']:
return None
content_type_id, object_id = data['item'].split(':')
content_type = ContentType.objects.get(pk=content_type_id)
model = content_type.model_class()
return model.objects.get(pk=object_id)
def get_content_types_queryset(self):
items_models = getattr(self, 'highlighted_content_items_models',
q = Q()
if items_models:
for app, models in items_models:
q = q | Q(app_label=app.lower(), model__in=[m.lower() for m in models])
return ContentType.objects.filter(q)
def save(self, commit=True):
self.instance.item = self.get_item()
return super(HighlightedContentItemForm, self).save(commit)