validate Projects field in organization
[redakcja.git] / apps / organizations / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of MIL/PEER, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from django import forms
7 from django.contrib.sites.models import Site
8 from django.utils.translation import ugettext as _
9
10 from redakcja.utlis import send_notify_email
11 from .models import Organization, UserCard, countries
12
13
14 class OrganizationForm(forms.ModelForm):
15     cts = countries
16
17     class Meta:
18         model = Organization
19         exclude = ['_html']
20
21     def save(self, commit=True):
22         new = self.instance.id is None
23         organization = super(OrganizationForm, self).save(commit=commit)
24         if new:
25             site = Site.objects.get_current()
26             send_notify_email(
27                 'New organization in MIL/PEER',
28                 '''New organization in MIL/PEER: %s. View their profile: https://%s%s.
29
30 --
31 MIL/PEER team.''' % (organization.name, site.domain, organization.get_absolute_url()))
32         return organization
33
34     def clean_projects(self):
35         projects = self.cleaned_data.get('projects', '')
36         lines = []
37         for line in projects.split('\n'):
38             line = line.strip()
39             if line:
40                 try:
41                     url, lang, desc = line.split(None, 2)
42                 except ValueError:
43                     raise forms.ValidationError(
44                         _('Each line has to consist of an Internet address, language and description, '
45                           'separated with spaces. Failed on: %s' % line))
46                 # naive check
47                 if '.' not in url or url.endswith('.'):
48                     raise forms.ValidationError(
49                         _('The first item in each line should be an Internet address. Failed on: %s') % url)
50                 if not url.startswith('http'):
51                     url = 'http://' + url
52                 lines.append(' '.join((url, lang, desc)))
53             else:
54                 lines.append('')
55         return '\n'.join(lines)
56
57
58 class UserCardForm(forms.ModelForm):
59     cts = countries
60
61     first_name = forms.CharField(required=False)
62     last_name = forms.CharField(required=False)
63
64     class Meta:
65         model = UserCard
66         exclude = ['_html', 'user']
67
68     def __init__(self, *args, **kwargs):
69         if 'instance' in kwargs:
70             kwargs['initial'] = {
71                 'first_name': kwargs['instance'].user.first_name,
72                 'last_name': kwargs['instance'].user.last_name,
73             }
74         super(UserCardForm, self).__init__(*args, **kwargs)
75
76     def save(self, *args, **kwargs):
77         self.instance.user.first_name = self.cleaned_data.get('first_name', '')
78         self.instance.user.last_name = self.cleaned_data.get('last_name', '')
79         self.instance.user.save()
80         return super(UserCardForm, self).save(*args, **kwargs)