solr conf to search events
[prawokultury.git] / migdal / forms.py
1 # -*- coding: utf-8 -*-
2 # This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django import forms
6 from django.utils.translation import ugettext_lazy as _, get_language
7 from migdal.models import Entry
8 from migdal.settings import TYPE_SUBMIT
9 from slughifi import slughifi
10 from django.core.mail import mail_managers
11 from django import template
12
13
14 def get_submit_form(*args, **kwargs):
15     lang = get_language()
16
17     class SubmitForm(forms.ModelForm):
18         class Meta:
19             model = Entry
20             fields = ['title_%s' % lang, 'lead_%s' % lang,
21                 'author', 'author_email', 'categories']
22             required = ['title_%s' % lang]
23
24         def __init__(self, *args, **kwargs):
25             super(SubmitForm, self).__init__(*args, **kwargs)
26             self.fields['title_%s' % lang].required = True
27             self.fields['lead_%s' % lang].required = True
28
29         def clean(self):
30             data = super(SubmitForm, self).clean()
31             data['type'] = TYPE_SUBMIT
32             orig_slug = slughifi(data.get('title_%s' % lang, ''))
33             slug = orig_slug
34             number = 2
35             while Entry.objects.filter(**{'slug_%s' % lang: slug}).exists():
36                 slug = "%s-%s" % (orig_slug, number)
37                 number += 1
38             data['slug_%s' % lang] = slug
39             self.cleaned_data = data
40             return data
41
42         def save(self, *args, **kwargs):
43             entry = super(SubmitForm, self).save(commit=False)
44             # Something's wrong with markup fields, they choke on None here.
45             for f in 'lead_en', 'lead_pl', 'body_en', 'body_pl':
46                 if getattr(entry, f) is None:
47                     setattr(entry, f, '')
48             for f in 'slug_%s' % lang, 'type':
49                 setattr(entry, f, self.cleaned_data[f])
50             entry.save()
51             entry = super(SubmitForm, self).save(*args, **kwargs)
52             mail_managers(u"Nowy wpis",
53                 template.loader.get_template(
54                     'migdal/mail/manager_new_entry.txt').render(
55                         template.Context({'object': entry})))
56
57     return SubmitForm(*args, **kwargs)