<commit_before>from django import forms
from django.utils.translation import ugettext_lazy as _, ugettext
from satchmo.configuration import config_value, config_get_group, SettingNotSet
from satchmo.contact.models import Contact, AddressBook, PhoneNumber
from satchmo.l10n.models import Country
from satchmo.shop.models import Config
from django.contrib.auth.models import User
from signals import satchmo_contact_location_changed
import datetime
import logging

log = logging.getLogger('satchmo.contact.forms')

selection = ''

class ContactInfoForm(forms.Form):
    email = forms.EmailField(max_length=75)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone = forms.CharField(max_length=30)
    addressee = forms.CharField(max_length=61, required=False)
    street1 = forms.CharField(max_length=30)
    street2 = forms.CharField(max_length=30, required=False)
    city = forms.CharField(max_length=30)
    state = forms.CharField(max_length=30, required=False)
    country = forms.ModelChoiceField(Country.objects.all(), required=False)
    postal_code = forms.CharField(max_length=10)
    copy_address = forms.BooleanField(required=False)
    ship_addressee = forms.CharField(max_length=61, required=False)
    ship_street1 = forms.CharField(max_length=30, required=False)
    ship_street2 = forms.CharField(max_length=30, required=False)
    ship_city = forms.CharField(max_length=30, required=False)
    ship_state = forms.CharField(max_length=30, required=False)
    ship_postal_code = forms.CharField(max_length=10, required=False)
    ship_country = forms.ModelChoiceField(Country.objects.all(), required=False)

    def __init__(self, countries, areas, contact, *args, **kwargs):
        self.shippable = True
        if kwargs.has_key('shippable'):
            self.shippable = kwargs['shippable']
            del(kwargs['shippable'])
        super(ContactInfoForm, self).__init__(*args, **kwargs)   
        if areas is not None and countries is None:
            log.debug('populating admin areas')
            areas = [(area.abbrev, area.name) for area in areas]
            self.fields['state'] = forms.ChoiceField(choices=areas, initial=selection)
            self.fields['ship_state'] = forms.ChoiceField(choices=areas, initial=selection, required=False)
        if countries is not None:
            self.fields['country'] = forms.ModelChoiceField(countries)
            if self.shippable:
                self.fields['ship_country'] = forms.ModelChoiceField(countries)

        shop_config = Config.objects.get_current()
        self._local_only = shop_config.in_country_only
        # country = shop_config.sales_country
        # if not country:
        #     self._default_country = Country.objects.get(iso2_code__iequals='US')
        # else:
        #     self._default_country = country
        country = shop_config.sales_country
        self._default_country = country.pk
        self.fields['country'].initial = country.pk
        self.fields['ship_country'].initial = country.pk
        self.contact = contact

    def clean_email(self):
        """Prevent account hijacking by disallowing duplicate emails."""
        email = self.cleaned_data.get('email', None)
        if self.contact:
            if self.contact.email and self.contact.email == email:
                return email
            users_with_email = Contact.objects.filter(email=email)
            if len(users_with_email) == 0:
                return email
            if len(users_with_email) > 1 or users_with_email[0].id != self.contact.id:
                raise forms.ValidationError(
                    ugettext("That email address is already in use."))
        return email
        
    def clean_state(self):
        data = self.cleaned_data['state']
        if self._local_only:
            country_pk = self._default_country
        else:
            if not 'country' in self.data:
                # The user didn't even submit a country, but this error will
                # be handled by the clean_country function
                return data
            country = self.data['country']
        country = Country.objects.get(pk=country_pk)
        if country.adminarea_set.filter(active=True).count() > 0:
            if not data or data == selection:
                raise forms.ValidationError(
                    self._local_only and _('This field is required.') \
                               or _('State is required for your country.'))
        return data

    def clean_ship_state(self):
        data = self.cleaned_data['ship_state']
        if self.cleaned_data['copy_address']:
            if 'state' in self.cleaned_data:
                self.cleaned_data['ship_state'] = self.cleaned_data['state']
            return self.cleaned_data['ship_state']

        if self._local_only:
            country_pk = self._default_country<commit_msg>fixing missing country_pk, closing #531<commit_after>from django import forms
from django.utils.translation import ugettext_lazy as _, ugettext
from satchmo.configuration import config_value, config_get_group, SettingNotSet
from satchmo.contact.models import Contact, AddressBook, PhoneNumber
from satchmo.l10n.models import Country
from satchmo.shop.models import Config
from django.contrib.auth.models import User
from signals import satchmo_contact_location_changed
import datetime
import logging

log = logging.getLogger('satchmo.contact.forms')

selection = ''

class ContactInfoForm(forms.Form):
    email = forms.EmailField(max_length=75)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone = forms.CharField(max_length=30)
    addressee = forms.CharField(max_length=61, required=False)
    street1 = forms.CharField(max_length=30)
    street2 = forms.CharField(max_length=30, required=False)
    city = forms.CharField(max_length=30)
    state = forms.CharField(max_length=30, required=False)
    country = forms.ModelChoiceField(Country.objects.all(), required=False)
    postal_code = forms.CharField(max_length=10)
    copy_address = forms.BooleanField(required=False)
    ship_addressee = forms.CharField(max_length=61, required=False)
    ship_street1 = forms.CharField(max_length=30, required=False)
    ship_street2 = forms.CharField(max_length=30, required=False)
    ship_city = forms.CharField(max_length=30, required=False)
    ship_state = forms.CharField(max_length=30, required=False)
    ship_postal_code = forms.CharField(max_length=10, required=False)
    ship_country = forms.ModelChoiceField(Country.objects.all(), required=False)

    def __init__(self, countries, areas, contact, *args, **kwargs):
        self.shippable = True
        if kwargs.has_key('shippable'):
            self.shippable = kwargs['shippable']
            del(kwargs['shippable'])
        super(ContactInfoForm, self).__init__(*args, **kwargs)   
        if areas is not None and countries is None:
            log.debug('populating admin areas')
            areas = [(area.abbrev, area.name) for area in areas]
            self.fields['state'] = forms.ChoiceField(choices=areas, initial=selection)
            self.fields['ship_state'] = forms.ChoiceField(choices=areas, initial=selection, required=False)
        if countries is not None:
            self.fields['country'] = forms.ModelChoiceField(countries)
            if self.shippable:
                self.fields['ship_country'] = forms.ModelChoiceField(countries)

        shop_config = Config.objects.get_current()
        self._local_only = shop_config.in_country_only
        # country = shop_config.sales_country
        # if not country:
        #     self._default_country = Country.objects.get(iso2_code__iequals='US')
        # else:
        #     self._default_country = country
        country = shop_config.sales_country
        self._default_country = country.pk
        self.fields['country'].initial = country.pk
        self.fields['ship_country'].initial = country.pk
        self.contact = contact

    def clean_email(self):
        """Prevent account hijacking by disallowing duplicate emails."""
        email = self.cleaned_data.get('email', None)
        if self.contact:
            if self.contact.email and self.contact.email == email:
                return email
            users_with_email = Contact.objects.filter(email=email)
            if len(users_with_email) == 0:
                return email
            if len(users_with_email) > 1 or users_with_email[0].id != self.contact.id:
                raise forms.ValidationError(
                    ugettext("That email address is already in use."))
        return email
        
    def clean_state(self):
        data = self.cleaned_data['state']
        if self._local_only:
            country_pk = self._default_country
        else:
            if not 'country' in self.data:
                # The user didn't even submit a country, but this error will
                # be handled by the clean_country function
                return data
            country_pk = self.data['country']
        country = Country.objects.get(pk=country_pk)
        if country.adminarea_set.filter(active=True).count() > 0:
            if not data or data == selection:
                raise forms.ValidationError(
                    self._local_only and _('This field is required.') \
                               or _('State is required for your country.'))
        return data

    def clean_ship_state(self):
        data = self.cleaned_data['ship_state']
        if self.cleaned_data['copy_address']:
            if 'state' in self.cleaned_data:
                self.cleaned_data['ship_state'] = self.cleaned_data['state']
            return self.cleaned_data['ship_state']

        if self._local_only:
            country_pk = self._default_country
{'fraction_non_alphanumeric': 0.09540241550796712, 'fraction_numerical': 0.00903278189383944, 'mean_word_length': 2.8507229386479094, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6056271', 'n_tokens_mistral': 2842, 'n_tokens_neox': 2760, 'n_words': 603}