<commit_before># -*- coding: utf-8 -*-

import logging

from django import forms
from django.core.urlresolvers import reverse

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.core.validators import URLValidator

from mongodbforms import DocumentForm

from django_select2.widgets import (Select2Widget,
                                    Select2MultipleWidget, )
                                    # HeavySelect2MultipleWidget)

from .models import (HomePreferences, ReadPreferences,
                     SelectorPreferences, StaffPreferences,
                     Folder, Subscription, Feed)

LOGGER = logging.getLogger(__name__)
User = get_user_model()


class FullUserCreationForm(forms.ModelForm):
    """ Like the django UserCreationForm,
        with optional first_name and last_name,
        and email too.

        .. note:: the ``username`` field from Django's ``UserCreationForm``
            is overriden by our Model's one. Thus the 30 chars limit
            doesn't apply.
    """

    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }

    email = forms.EmailField()
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
                                widget=forms.PasswordInput,
                                help_text=_("Enter the same password as "
                                            "above, for verification."))

    class Meta:
        model  = User
        fields = ['first_name', 'last_name',
                  'username', 'email',
                  'password1', '<PASSWORD>', ]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'])
        return password2

    def save(self, commit=True):
        user = super(FullUserCreationForm, self).save(commit=False)

        user.set_password(self.cleaned_data["password1"])
        user.email      = self.cleaned_data["email"]
        user.first_name = self.cleaned_data["first_name"]
        user.last_name  = self.cleaned_data["last_name"]

        if commit:
            user.save()

        return user


class UserProfileEditForm(forms.ModelForm):

    class Meta:
        model  = User
        fields = ['first_name', 'last_name', ]


class HomePreferencesForm(DocumentForm):

    class Meta:
        model = HomePreferences

        # Other fields are not yet ready
        exclude = ('style', )


class ReadPreferencesForm(DocumentForm):

    class Meta:
        model = ReadPreferences


class SelectorPreferencesForm(DocumentForm):

    class Meta:
        model = SelectorPreferences


class StaffPreferencesForm(DocumentForm):

    class Meta:
        model = StaffPreferences


class OnlyNameChoiceField(forms.ModelChoiceField):
    """ In forms, we need something much simpler
        than the `__unicode__()` output. """

    def label_from_instance(self, obj):

        root = obj.owner.root_folder

        # OMG. Please don't do this anywhere else. How ugly it is.
        if obj.parent == root:
            prefix = u''
        elif obj.parent.parent == root:
            prefix = u' ' * 8
        elif obj.parent.parent.parent == root:
            prefix = u' ' * 16
        elif obj.parent.parent.parent.parent == root:
            prefix = u' ' * 24
        elif obj.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 32
        elif obj.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 40
        elif obj.parent.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 48
        else:
            prefix = u' ' * 56

        return prefix + obj.name


class OnlyNameMultipleChoiceField(forms.ModelMultipleChoiceField):
    """ In forms, we need something much simpler
        than the `__unicode__()` output. """

    def label_from_instance(self, obj):

        try:
            root = obj.owner.root_folder

        except AttributeError:
            return obj.name

        # OMG. Please don't do this anywhere else. How ugly it is.
        if obj.parent == root:
            prefix = u''
        elif obj.parent.parent == root:
            prefix = u' ' * 8
        elif obj.parent.parent.parent == root:
            prefix = u' ' * 16
        elif obj.parent.parent.parent.parent == root:
            prefix = u' ' * 24
        elif obj.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 32
        elif obj.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 40
        elif obj.parent.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 48
        else:
            prefix = u' ' * 56

        return prefix + obj.name


class ManageFolderForm(DocumentForm):
    parent = OnlyNameChoiceField(queryset=Folder.objects.all(),
                                 empty_label=_(u'(None)'),
                                 required=False, widget=Select2Widget())

    subscriptions = OnlyNameMultipleChoiceField(
        label=_(u'Subscriptions'), queryset=Subscription.objects.none(),
        required=False, widget=Select2MultipleWidget(),
        help_text=_(u'These are the ones held directly by the folder; they '
                    u'are displayed above subfolders. There can be none, if '
                    u'you prefer dispatching your subscriptions in subfolders '
                    u'only.'))

    class Meta:
        model = Folder
        fields = ('name', 'parent', )
        widgets = {
            'name': forms.TextInput(),
        }

    def __init__(self, *args, **kwargs):

        self.folder_owner = kwargs.pop('owner')

        super(ManageFolderForm, self).__init__(*args, **kwargs)

        folders_tree = self.folder_owner.get_folders_tree(for_parent=True)

        if self.instance.id:<commit_msg>Again, a missing label. I thought Django would have taken the `verbose_name` of the field. But it seems “not when a field with the same name as a model attribute is manually added to a `ModelForm`”. Still, strange.<commit_after># -*- coding: utf-8 -*-

import logging

from django import forms
from django.core.urlresolvers import reverse

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.core.validators import URLValidator

from mongodbforms import DocumentForm

from django_select2.widgets import (Select2Widget,
                                    Select2MultipleWidget, )
                                    # HeavySelect2MultipleWidget)

from .models import (HomePreferences, ReadPreferences,
                     SelectorPreferences, StaffPreferences,
                     Folder, Subscription, Feed)

LOGGER = logging.getLogger(__name__)
User = get_user_model()


class FullUserCreationForm(forms.ModelForm):
    """ Like the django UserCreationForm,
        with optional first_name and last_name,
        and email too.

        .. note:: the ``username`` field from Django's ``UserCreationForm``
            is overriden by our Model's one. Thus the 30 chars limit
            doesn't apply.
    """

    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }

    email = forms.EmailField()
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
                                widget=forms.PasswordInput,
                                help_text=_("Enter the same password as "
                                            "above, for verification."))

    class Meta:
        model  = User
        fields = ['first_name', 'last_name',
                  'username', 'email',
                  'password1', 'password2', ]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'])
        return password2

    def save(self, commit=True):
        user = super(FullUserCreationForm, self).save(commit=False)

        user.set_password(self.cleaned_data["password1"])
        user.email      = self.cleaned_data["email"]
        user.first_name = self.cleaned_data["first_name"]
        user.last_name  = self.cleaned_data["last_name"]

        if commit:
            user.save()

        return user


class UserProfileEditForm(forms.ModelForm):

    class Meta:
        model  = User
        fields = ['first_name', 'last_name', ]


class HomePreferencesForm(DocumentForm):

    class Meta:
        model = HomePreferences

        # Other fields are not yet ready
        exclude = ('style', )


class ReadPreferencesForm(DocumentForm):

    class Meta:
        model = ReadPreferences


class SelectorPreferencesForm(DocumentForm):

    class Meta:
        model = SelectorPreferences


class StaffPreferencesForm(DocumentForm):

    class Meta:
        model = StaffPreferences


class OnlyNameChoiceField(forms.ModelChoiceField):
    """ In forms, we need something much simpler
        than the `__unicode__()` output. """

    def label_from_instance(self, obj):

        root = obj.owner.root_folder

        # OMG. Please don't do this anywhere else. How ugly it is.
        if obj.parent == root:
            prefix = u''
        elif obj.parent.parent == root:
            prefix = u' ' * 8
        elif obj.parent.parent.parent == root:
            prefix = u' ' * 16
        elif obj.parent.parent.parent.parent == root:
            prefix = u' ' * 24
        elif obj.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 32
        elif obj.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 40
        elif obj.parent.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 48
        else:
            prefix = u' ' * 56

        return prefix + obj.name


class OnlyNameMultipleChoiceField(forms.ModelMultipleChoiceField):
    """ In forms, we need something much simpler
        than the `__unicode__()` output. """

    def label_from_instance(self, obj):

        try:
            root = obj.owner.root_folder

        except AttributeError:
            return obj.name

        # OMG. Please don't do this anywhere else. How ugly it is.
        if obj.parent == root:
            prefix = u''
        elif obj.parent.parent == root:
            prefix = u' ' * 8
        elif obj.parent.parent.parent == root:
            prefix = u' ' * 16
        elif obj.parent.parent.parent.parent == root:
            prefix = u' ' * 24
        elif obj.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 32
        elif obj.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 40
        elif obj.parent.parent.parent.parent.parent.parent.parent == root:
            prefix = u' ' * 48
        else:
            prefix = u' ' * 56

        return prefix + obj.name


class ManageFolderForm(DocumentForm):
    parent = OnlyNameChoiceField(queryset=Folder.objects.all(),
                                 empty_label=_(u'(None)'),
                                 label=_(u'Parent folder'),
                                 required=False, widget=Select2Widget())

    subscriptions = OnlyNameMultipleChoiceField(
        label=_(u'Subscriptions'), queryset=Subscription.objects.none(),
        required=False, widget=Select2MultipleWidget(),
        help_text=_(u'These are the ones held directly by the folder; they '
                    u'are displayed above subfolders. There can be none, if '
                    u'you prefer dispatching your subscriptions in subfolders '
                    u'only.'))

    class Meta:
        model = Folder
        fields = ('name', 'parent', )
        widgets = {
            'name': forms.TextInput(),
        }

    def __init__(self, *args, **kwargs):

        self.folder_owner = kwargs.pop('owner')

        super(ManageFolderForm, self).__init__(*args, **kwargs)

        folders_tree = self.folder_owner.get_folders_tree(for_parent=True)

        if self.instance.id:
{'fraction_non_alphanumeric': 0.097429387496033, 'fraction_numerical': 0.007854649317676928, 'mean_word_length': 2.060208788540908, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 13, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6305268', 'n_tokens_mistral': 3478, 'n_tokens_neox': 3288, 'n_words': 876}