# -*- coding: utf-8 -*- """Forms for emencia.django.newsletter""" from django import forms from django.utils.translation import ugettext_lazy as _ from django.http import Http404 from emencia.django.newsletter.models import Contact, ContactSettings from emencia.django.newsletter.models import MailingList from functions.form_check import translit_with_separator as tr from theme.models import Theme from country.models import Country, Area from city.models import City class MailingListSubscriptionForm(forms.ModelForm): """Form for subscribing to a mailing list""" # Notes : This form will not check the uniquess of # the 'email' field, by defining it explictly and setting # it the Meta.exclude list, for allowing registration # to a mailing list even if the contact already exists. # Then the contact is always added to the subscribers field # of the mailing list because it will be cleaned with no # double. email = forms.EmailField(label=_('Email'), max_length=75) def save(self, mailing_list): data = self.cleaned_data contact, created = Contact.objects.get_or_create( email=data['email'], defaults={'first_name': data['first_name'], 'last_name': data['last_name']}) mailing_list.subscribers.add(contact) mailing_list.unsubscribers.remove(contact) class Meta: model = Contact fields = ('first_name', 'last_name') exclude = ('email',) class AllMailingListSubscriptionForm(MailingListSubscriptionForm): """Form for subscribing to all mailing list""" mailing_lists = forms.ModelMultipleChoiceField( queryset=MailingList.objects.all(), initial=[obj.id for obj in MailingList.objects.all()], label=_('Mailing lists'), widget=forms.CheckboxSelectMultiple()) def save(self, mailing_list): data = self.cleaned_data contact, created = Contact.objects.get_or_create( email=data['email'], defaults={'first_name': data['first_name'], 'last_name': data['last_name']}) for mailing_list in data['mailing_lists']: mailing_list.subscribers.add(contact) mailing_list.unsubscribers.remove(contact) class ContactForm(forms.ModelForm): email = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': _(u'Ваш e-mail')})) first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': _(u'Ваше имя')})) class Meta: model = Contact fields = ('email', 'first_name', ) class ContactSettingsForm(forms.ModelForm): theme = forms.MultipleChoiceField(choices=[(str(item.id), item.name) for item in list(Theme.objects.language().all())], widget=forms.CheckboxSelectMultiple(attrs={'class': 'pr-checkbox'}), required=False) class Meta: model = ContactSettings fields = ('exponent_practicum', 'organiser_practicum', 'theme') def clean_theme(self): theme = self.cleaned_data.get('theme') if theme: return Theme.objects.filter(id__in=theme) else: return Theme.objects.none() class ContactFilterForm(forms.Form): email = forms.EmailField( label="Email", max_length=255, required=False, widget=forms.TextInput(attrs={'class':'input-xlarge search-query','placeholder': 'Email'}) ) theme = forms.MultipleChoiceField( label="Тематика", choices=[(t.id, t.name) for t in Theme.objects.language()], required=False ) country = forms.MultipleChoiceField( label="Страна", choices=[(c.id, c.name) for c in list(set(Country.objects.language('ru').all()))], required=False ) city = forms.MultipleChoiceField( label="Город", choices=[(c.id, c.name) for c in list(set(City.objects.language('ru').filter(contactsettings__isnull=False)))], required=False ) area = forms.MultipleChoiceField( label="Area", choices=[(c.id, c.name) for c in list(set(Area.objects.language()))], required=False ) mailinglist = forms.ChoiceField( choices=[(ml.id, ml.name) for ml in MailingList.objects.all()], label="Список рассылки", required=False ) active = forms.BooleanField(label="Подтверждена подписка", required=False) valid = forms.BooleanField(label="Валидный Email", required=False) def filter(self): title = 'contact list ' qs = Contact.objects.all() if self.cleaned_data.get('mailinglist'): qs = qs.filter(mailinglist_subscriber__id=self.cleaned_data['mailinglist']) title += " mailinglist: %s" % MailingList.objects.get(id=self.cleaned_data['mailinglist']).name if self.cleaned_data.get('country'): qs = qs.filter(contactsettings__country__id__in=self.cleaned_data['country']) title += " countries: %s" % ','.join([obj.url for obj in Country.objects.language().filter(id__in=self.cleaned_data['country'])]) if self.cleaned_data.get('email'): qs = qs.filter(email__icontains=self.cleaned_data['email']) if self.cleaned_data.get('theme'): qs = qs.filter(contactsettings__theme__id__in=self.cleaned_data['theme']) title += " themes: %s" % ','.join([obj.url for obj in Theme.objects.language().filter(id__in=self.cleaned_data['theme'])]) if self.cleaned_data.get('city'): qs = qs.filter(contactsettings__city__id__in=self.cleaned_data['city']) title += " cities: %s" % ','.join([obj.url for obj in Country.objects.language().filter(id__in=self.cleaned_data['country'])]) if self.cleaned_data.get('area'): qs = qs.filter(contactsettings__area__id__in=self.cleaned_data['area']) title += " geo area: %s" % ','.join([tr(obj.name) for obj in Area.objects.language('en').filter(id__in=self.cleaned_data['area'])]) if self.cleaned_data.get('active'): title = ' active ' + title qs = qs.filter(activated=True) if self.cleaned_data.get('valid'): title = 'valid e-mail ' + title qs = qs.filter(valid=True) return qs, title import xlrd COUNTRY_CHOICES = [(c.id, c.name) for c in list(set(Country.objects.language('ru').all()))] COUNTRY_CHOICES.insert(0, ('', 'Страна')) class ContactImportForm(forms.Form): excel_file = forms.FileField(label='Выберите файл') activated = forms.BooleanField(label="Активные", required=False) is_tester = forms.BooleanField(label="Тестовые", required=False) country = forms.ChoiceField(label="Страна", choices=COUNTRY_CHOICES, required=False) def save(self): data = self.cleaned_data country_id = self.cleaned_data.get('country') country = None if country_id: country = Country.objects.get(id=country_id) activated = data['activated'] is_tester = data['is_tester'] f = data['excel_file'] book = xlrd.open_workbook(file_contents=f.read()) sheet = book.sheet_by_index(0) row_list = [sheet.row_values(row_number) for row_number in range(1, sheet.nrows)] for row in row_list: c = Contact(email = row[0], first_name=row[1].split()[0], last_name=row[1].split()[-1], tester=is_tester, activated=activated, valid=True, subscriber=True) try: c.save() except: continue cs = ContactSettings() cs.contact = c cs.save() if country: cs.country.add(country) cs.save() # do not watch # cursor = db.cursor() # sql = u""" # INSERT IGNORE # INTO newsletter_contact(first_name, email, activated, tester, creation_date, last_name) # VALUES %s;""" % u','.join([u"('%s', '%s', '%s', '%s', NOW(), '')" % (row[1], row[0], str(activated).upper(), str(is_tester).upper()) for row in row_list]) # cursor.execute(sql)