diff options
Diffstat (limited to 'ishtar_common/forms_common.py')
-rw-r--r-- | ishtar_common/forms_common.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/ishtar_common/forms_common.py b/ishtar_common/forms_common.py index 47e976452..43652ba07 100644 --- a/ishtar_common/forms_common.py +++ b/ishtar_common/forms_common.py @@ -27,6 +27,7 @@ import tempfile from django import forms from django.conf import settings from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType from django.core import validators from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist @@ -1276,3 +1277,58 @@ AuthorFormset = formset_factory(AuthorFormSelection, can_delete=True, AuthorFormset.form_label = _("Authors") AuthorFormset.form_admin_name = _(u"Authors") AuthorFormset.form_slug = "authors" + + +class SearchQueryForm(forms.Form): + query = forms.CharField(max_length=None, label=_(u"Query"), disabled=True, + initial='*') + search_query = forms.ChoiceField(label=_(u"Search query"), required=False, + choices=[]) + label = forms.CharField(max_length=None, label=_(u"Name"), required=False) + is_alert = forms.BooleanField(label=_(u"Is an alert"), required=False) + create_or_update = forms.ChoiceField( + choices=(('create', _(u"Create")), + ('update', _(u"Update"))), initial='create') + + def __init__(self, profile, content_type, *args, **kwargs): + self.profile = profile + self.content_type = content_type + super(SearchQueryForm, self).__init__(*args, **kwargs) + self.fields['search_query'].choices = [ + (c.pk, c.label) for c in models.SearchQuery.objects.filter( + content_type=content_type, profile=profile).all()] + if not self.fields['search_query'].choices: + self.fields.pop('search_query') + + def clean(self): + data = self.cleaned_data + if data['create_or_update'] == 'create' and not data['label']: + raise forms.ValidationError(_(u"A label is required for a new " + u"search query.")) + elif data['create_or_update'] == 'update': + if not data['search_query']: + raise forms.ValidationError(_(u"Select the search query to " + u"update")) + q = models.SearchQuery.objects.filter( + profile=self.profile, content_type=self.content_type, + pk=data['search_query']) + if not q.count(): + raise forms.ValidationError(_(u"Query does not exist.")) + return data + + def save(self): + data = self.cleaned_data + if data['create_or_update'] == 'create': + sq = models.SearchQuery.objects.create( + label=data['label'], query=data['query'], profile=self.profile, + content_type=self.content_type, is_alert=data['is_alert']) + else: + try: + sq = models.SearchQuery.objects.get( + profile=self.profile, content_type=self.content_type, + pk=data['search_query']) + except models.SearchQuery.DoesNotExist: + raise forms.ValidationError(_(u"Query does not exist.")) + sq.query = data['query'] + sq.save() + return sq |