7c93ea8fd5d6f0a750506dd92914eaad0b821109
[django-migdal.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.contrib.sites.models import Site
6 from django.core.mail import mail_managers
7 from django import forms
8 from django import template
9 from django.utils.translation import ugettext_lazy as _, get_language
10 from fnpdjango.utils.text.slughifi import slughifi
11 from migdal.models import Entry
12 from migdal import app_settings
13
14
15 def get_submit_form(*args, **kwargs):
16     lang = get_language()
17
18     class SubmitForm(forms.ModelForm):
19         class Meta:
20             model = Entry
21             fields = ['title_%s' % lang, 'lead_%s' % lang,
22                 'author', 'author_email', 'categories']
23             required = ['title_%s' % lang]
24
25         def __init__(self, *args, **kwargs):
26             super(SubmitForm, self).__init__(*args, **kwargs)
27             title = self.fields['title_%s' % lang]
28             title.required = True
29             title.label = _('Title')
30             lead = self.fields['lead_%s' % lang]
31             lead.required = True
32             lead.label = _('Content')
33
34         def clean(self):
35             data = super(SubmitForm, self).clean()
36             data['type'] = app_settings.TYPE_SUBMIT
37             orig_slug = slughifi(data.get('title_%s' % lang, ''))
38             slug = orig_slug
39             number = 2
40             while Entry.objects.filter(**{'slug_%s' % lang: slug}).exists():
41                 slug = "%s-%s" % (orig_slug, number)
42                 number += 1
43             data['slug_%s' % lang] = slug
44             self.cleaned_data = data
45             return data
46
47         def save(self, *args, **kwargs):
48             entry = super(SubmitForm, self).save(commit=False)
49             # Something's wrong with markup fields, they choke on None here.
50             for f in 'lead_en', 'lead_pl', 'body_en', 'body_pl':
51                 if getattr(entry, f) is None:
52                     setattr(entry, f, '')
53             for f in 'slug_%s' % lang, 'type':
54                 setattr(entry, f, self.cleaned_data[f])
55             entry.save()
56             entry = super(SubmitForm, self).save(*args, **kwargs)
57             mail_managers(u"Nowy wpis",
58                 template.loader.get_template(
59                     'migdal/mail/manager_new_entry.txt').render(
60                         template.Context({
61                             'object': entry,
62                             'site': Site.objects.get_current(),
63                         })))
64
65     return SubmitForm(*args, **kwargs)