示例#1
0
文件: forms.py 项目: zaid100/tendenci
def build_settings_form(user, settings):
    """
        Create a set of fields and builds a form class
        returns SettingForm class
    """
    fields = OrderedDict()
    for setting in settings:
        setting_label = mark_safe('{0} <a href="#id_{1}" title="Permalink to this setting"><i class="fa fa-link" aria-hidden="true"></i></a>'.format(
                                    setting.label, setting.name))

        # Do not display standard regform settings
        if setting.scope_category == 'events' and setting.name.startswith('regform_'):
            continue

        try:
            setting_value = force_text(setting.get_value())
        except DjangoUnicodeDecodeError:
            setting_value = ''

        if setting.input_type in ['text', 'textarea']:
            options = {
                'label': setting_label,
                'help_text': setting.description,
                'initial': setting_value,
                'required': False,
                'label_suffix': "",
            }
            if setting.input_type == 'textarea':
                options['widget'] = forms.Textarea(attrs={'rows': 5, 'cols': 30})

            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.CharField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.CharField(**options)})

        elif setting.input_type in ['select', 'selectmultiple']:
            if setting.input_value == '<form_list>':
                choices = get_form_list(user)
                required = False
            elif setting.input_value == '<box_list>':
                choices = get_box_list(user)
                required = False
            elif setting.input_value == '<group_list>':
                choices, initial = get_group_list(user)
                required = True
                if not setting_value:
                    setting_value = initial
            elif setting.input_value == '<timezone_list>':
                choices = get_timezone_choices()
                required = True
                if not setting_value:
                    setting_value = django_settings.TIME_ZONE
            elif setting.input_value == '<language_list>':
                choices = get_languages_with_local_name()
                required = True
            elif setting.input_value == '<country_list>':
                choices = (('', '-----------'),) + tuple(COUNTRIES)
                required = False
                if setting.get_value() and  setting.name == 'countrylistinitialchoices':
                    setting_value = literal_eval(setting.get_value())
            else:
                # Allow literal_eval in settings in order to pass a list from the setting
                # This is useful if you want different values and labels for the select options
                try:
                    choices = tuple([(k, v)for k, v in literal_eval(setting.input_value)])
                    required = False

                    # By adding #<box_list> on to the end of a setting, this will append the boxes
                    # as select items in the list as well.
                    if '<box_list>' in setting.input_value:
                        box_choices = get_box_list(user)[1:]
                        choices = (('Content', choices), ('Boxes', box_choices))
                except:
                    choices = tuple([(s.strip(), s.strip())for s in setting.input_value.split(',')])
                    required = True

            options = {
                'label': setting_label,
                'help_text': setting.description,
                'initial': setting_value,
                'choices': choices,
                'required': required,
                'label_suffix': "",
            }
            if setting.client_editable or user.is_superuser:
                if setting.input_type == 'selectmultiple':
                    fields.update({"%s" % setting.name: forms.MultipleChoiceField(**options)})
                else:
                    fields.update({"%s" % setting.name: forms.ChoiceField(**options)})

        elif setting.input_type == 'file':
            from tendenci.apps.files.models import File as TendenciFile
            file_display = ''
            try:
                try:
                    val = int(setting_value)
                except ValueError:
                    val = 0

                try:
                    tfile = TendenciFile.objects.get(pk=val)
                except Exception:
                    tfile = None

                if tfile:
                    if tfile.file.name.lower().endswith(('.jpg', '.jpe', '.png', '.gif', '.svg')):
                        tfile_alt = tfile.file.name.lower()[:-4]
                        file_display = '<img src="/files/%s/" alt="%s" title="%s">' % (tfile.pk, tfile_alt, tfile_alt)
                    else:
                        file_display = tfile.file.name
            except TendenciFile.DoesNotExist:
                file_display = "No file"
            options = {
                'label': setting_label,
                'help_text': "%s<br> Current File: %s" % (setting.description, file_display),
                #'initial': tfile and tfile.file, # Removed this so the file doesn't save over and over
                'required': False,
                'label_suffix': "",
            }
            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.FileField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.FileField(**options)})

    attributes = {
        'settings': settings,
        'base_fields': fields,
        'clean': clean_settings_form,
        'save': save_settings_form,
        'user': user,
    }
    return type('SettingForm', (forms.BaseForm,), attributes)
示例#2
0
class ProfileForm(TendenciBaseForm):

    first_name = forms.CharField(
        label=_("First Name"),
        max_length=100,
        error_messages={'required': _('First Name is a required field.')})
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=100,
        error_messages={'required': _('Last Name is a required field.')})
    email = EmailVerificationField(
        label=_("Email"),
        error_messages={'required': _('Email is a required field.')})
    email2 = EmailVerificationField(label=_("Secondary Email"), required=False)

    initials = forms.CharField(label=_("Initial"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '10'}))
    display_name = forms.CharField(
        label=_("Display name"),
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    url = forms.CharField(label=_("Web Site"),
                          max_length=100,
                          required=False,
                          widget=forms.TextInput(attrs={'size': '40'}))
    company = forms.CharField(
        label=_("Company"),
        max_length=100,
        required=False,
        error_messages={'required': _('Company is a required field.')},
        widget=forms.TextInput(attrs={'size': '45'}))
    department = forms.CharField(label=_("Department"),
                                 max_length=100,
                                 required=False,
                                 widget=forms.TextInput(attrs={'size': '35'}))
    address = forms.CharField(
        label=_("Address"),
        max_length=150,
        required=False,
        error_messages={'required': _('Address is a required field.')},
        widget=forms.TextInput(attrs={'size': '45'}))
    address2 = forms.CharField(label=_("Address2"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '40'}))
    city = forms.CharField(
        label=_("City"),
        max_length=50,
        required=False,
        error_messages={'required': _('City is a required field.')},
        widget=forms.TextInput(attrs={'size': '15'}))
    state = forms.CharField(
        label=_("State"),
        max_length=50,
        required=False,
        error_messages={'required': _('State is a required field.')},
        widget=forms.TextInput(attrs={'size': '5'}))
    zipcode = forms.CharField(
        label=_("Zipcode"),
        max_length=50,
        required=False,
        error_messages={'required': _('Zipcode is a required field.')},
        widget=forms.TextInput(attrs={'size': '10'}))
    country = CountrySelectField(label=_("Country"), required=False)

    address_2 = forms.CharField(label=_("Address"),
                                max_length=64,
                                required=False,
                                widget=forms.TextInput(attrs={'size': '45'}))
    address2_2 = forms.CharField(label=_("Address2"),
                                 max_length=64,
                                 required=False,
                                 widget=forms.TextInput(attrs={'size': '40'}))
    city_2 = forms.CharField(label=_("City"),
                             max_length=35,
                             required=False,
                             widget=forms.TextInput(attrs={'size': '15'}))
    state_2 = forms.CharField(label=_("State"),
                              max_length=35,
                              required=False,
                              widget=forms.TextInput(attrs={'size': '5'}))
    zipcode_2 = forms.CharField(label=_("Zipcode"),
                                max_length=16,
                                required=False,
                                widget=forms.TextInput(attrs={'size': '10'}))
    country_2 = CountrySelectField(label=_("Country"), required=False)

    mailing_name = forms.CharField(
        label=_("Mailing Name"),
        max_length=120,
        required=False,
        error_messages={'required': _('Mailing name is a required field.')},
        widget=forms.TextInput(attrs={'size': '30'}))

    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        help_text=
        _("Required. Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_)."
          ),
        error_messages={
            'invalid':
            _('Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_).'
              )
        })

    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(attrs=attrs_dict))
    password2 = forms.CharField(
        label=_("Password (again)"),
        widget=forms.PasswordInput(attrs=attrs_dict),
        help_text=_("Enter the same password as above, for verification."))
    security_level = forms.ChoiceField(initial="user",
                                       choices=(
                                           ('user', _('User')),
                                           ('staff', _('Staff')),
                                           ('superuser', _('Superuser')),
                                       ))
    interactive = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Interactive'),
                                        (0, _('Not Interactive (no login)')),
                                    ))
    direct_mail = forms.ChoiceField(initial=True,
                                    choices=(
                                        (True, _('Yes')),
                                        (False, _('No')),
                                    ))
    notes = forms.CharField(label=_("Notes"),
                            max_length=1000,
                            required=False,
                            widget=forms.Textarea(attrs={'rows': '3'}))
    admin_notes = forms.CharField(label=_("Admin Notes"),
                                  max_length=1000,
                                  required=False,
                                  widget=forms.Textarea(attrs={'rows': '3'}))
    language = forms.ChoiceField(initial="en",
                                 choices=get_languages_with_local_name())
    dob = forms.DateField(required=False,
                          widget=SelectDateWidget(None,
                                                  list(range(1920,
                                                             THIS_YEAR))))

    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    class Meta:
        model = Profile
        fields = (
            'salutation',
            'first_name',
            'last_name',
            'username',
            'password1',
            'password2',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'email',
            'email2',
            'company',
            'position_title',
            'position_assignment',
            'display_name',
            'hide_in_search',
            'hide_phone',
            'hide_email',
            'hide_address',
            'initials',
            'sex',
            'mailing_name',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'county',
            'country',
            'address_2',
            'address2_2',
            'city_2',
            'state_2',
            'zipcode_2',
            'county_2',
            'country_2',
            'url',
            'dob',
            'ssn',
            'spouse',
            'time_zone',
            'language',
            'department',
            'education',
            'student',
            'direct_mail',
            'notes',
            'interactive',
            'allow_anonymous_view',
            'admin_notes',
            'security_level',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        if 'user_this' in kwargs:
            self.user_this = kwargs.pop('user_this', None)
        else:
            self.user_this = None

        if 'user_current' in kwargs:
            self.user_current = kwargs.pop('user_current', None)
        else:
            self.user_current = None

        if 'required_fields_list' in kwargs:
            self.required_fields_list = kwargs.pop('required_fields_list',
                                                   None)
        else:
            self.required_fields_list = None

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

        if self.user_this:
            self.fields['first_name'].initial = self.user_this.first_name
            self.fields['last_name'].initial = self.user_this.last_name
            self.fields['username'].initial = self.user_this.username
            self.fields['email'].initial = self.user_this.email

            if self.user_this.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.user_this.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.user_this.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

            del self.fields['password1']
            del self.fields['password2']

            if not self.user_current.profile.is_superuser:
                del self.fields['admin_notes']
                del self.fields['security_level']
                del self.fields['status_detail']

            if self.user_current.profile.is_superuser and self.user_current == self.user_this:
                self.fields['security_level'].choices = (('superuser',
                                                          _('Superuser')), )

        if not self.user_current.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        # we make first_name, last_name, email, username and password as required field regardless
        # the rest of fields will be decided by the setting - UsersRequiredFields
        if self.required_fields_list:
            for field in self.required_fields_list:
                for myfield in self.fields:
                    if field == self.fields[myfield].label:
                        self.fields[myfield].required = True
                        continue

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        """
        try:
            user = User.objects.get(username=self.cleaned_data['username'])
            if self.user_this and user.id == self.user_this.id and user.username == self.user_this.username:
                return self.cleaned_data['username']
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.

        """
        if not self.user_this:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, request, user_edit, *args, **kwargs):
        """
        Create a new user then create the user profile
        """
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        params = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
        }

        if not self.user_this:
            password = self.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            self.instance.user = new_user
            update_user(new_user, **params)
        else:
            # for update_subscription
            self.instance.old_email = user_edit.email

            params.update({'username': username})
            update_user(user_edit, **params)

        if not self.instance.id:
            self.instance.creator = request.user
            self.instance.creator_username = request.user.username
        self.instance.owner = request.user
        self.instance.owner_username = request.user.username

        return super(ProfileForm, self).save(*args, **kwargs)
示例#3
0
文件: forms.py 项目: dco5/tendenci
def build_settings_form(user, settings):
    """
        Create a set of fields and builds a form class
        returns SettingForm class
    """
    fields = OrderedDict()
    for setting in settings:

        # Do not display standard regform settings
        if setting.scope_category == 'events' and setting.name.startswith('regform_'):
            continue

        try:
            setting_value = force_unicode(setting.get_value())
        except DjangoUnicodeDecodeError:
            setting_value = ''

        if setting.input_type in ['text', 'textarea']:
            options = {
                'label': setting.label,
                'help_text': setting.description,
                'initial': setting_value,
                'required': False
            }
            if setting.input_type == 'textarea':
                options['widget'] = forms.Textarea(attrs={'rows': 5, 'cols': 30});

            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.CharField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.CharField(**options)})
            
        elif setting.input_type in ['select', 'selectmultiple']:
            if setting.input_value == '<form_list>':
                choices = get_form_list(user)
                required = False
            elif setting.input_value == '<box_list>':
                choices = get_box_list(user)
                required = False
            elif setting.input_value == '<group_list>':
                choices, initial = get_group_list(user)
                required = True
                if not setting_value:
                    setting_value = initial
            elif setting.input_value == '<timezone_list>':
                choices = zones.PRETTY_TIMEZONE_CHOICES
                required = True
            elif setting.input_value == '<language_list>':
                choices = get_languages_with_local_name()
                required = True
            elif setting.input_value == '<country_list>':
                choices = (('', '-----------'),) + tuple(COUNTRIES)
                required = False
            else:
                # Allow literal_eval in settings in order to pass a list from the setting
                # This is useful if you want different values and labels for the select options
                try:
                    choices = tuple([(k, v)for k, v in literal_eval(setting.input_value)])
                    required = False

                    # By adding #<box_list> on to the end of a setting, this will append the boxes
                    # as select items in the list as well.
                    if '<box_list>' in setting.input_value:
                        box_choices = get_box_list(user)[1:]
                        choices = (('Content', choices), ('Boxes', box_choices))
                except:
                    choices = tuple([(s.strip(), s.strip())for s in setting.input_value.split(',')])
                    required = True

            options = {
                'label': setting.label,
                'help_text': setting.description,
                'initial': setting_value,
                'choices': choices,
                'required': required,
            }
            if setting.client_editable or user.is_superuser:
                if setting.input_type == 'selectmultiple':
                    fields.update({"%s" % setting.name: forms.MultipleChoiceField(**options)})
                else:
                    fields.update({"%s" % setting.name: forms.ChoiceField(**options)})

        elif setting.input_type == 'file':
            from tendenci.apps.files.models import File as TendenciFile
            file_display = ''
            try:
                try:
                    val = int(setting_value)
                except ValueError:
                    val = 0

                try:
                    tfile = TendenciFile.objects.get(pk=val)
                except Exception:
                    tfile = None

                if tfile:
                    if tfile.file.name.lower().endswith(('.jpg', '.jpe', '.png', '.gif', '.svg')):
                        tfile_alt = tfile.file.name.lower()[:-4]
                        file_display = '<img src="/files/%s/" alt="%s" title="%s">' % (tfile.pk, tfile_alt, tfile_alt)
                    else:
                        file_display = tfile.file.name
            except TendenciFile.DoesNotExist:
                file_display = "No file"
            options = {
                'label': setting.label,
                'help_text': "%s<br> Current File: %s" % (setting.description, file_display),
                #'initial': tfile and tfile.file, # Removed this so the file doesn't save over and over
                'required': False
            }
            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.FileField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.FileField(**options)})

    attributes = {
        'settings': settings,
        'base_fields': fields,
        'clean': clean_settings_form,
        'save': save_settings_form,
        'user': user,
    }
    return type('SettingForm', (forms.BaseForm,), attributes)
示例#4
0
class ProfileAdminForm(TendenciBaseForm):

    first_name = forms.CharField(
        label=_("First Name"),
        max_length=100,
        error_messages={'required': _('First Name is a required field.')})
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=100,
        error_messages={'required': _('Last Name is a required field.')})
    email = EmailVerificationField(
        label=_("Email"),
        error_messages={'required': _('Email is a required field.')})
    email2 = EmailVerificationField(label=_("Secondary Email"), required=False)

    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        help_text=
        _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."
          ))
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(attrs=attrs_dict))
    password2 = forms.CharField(
        label=_("Password (again)"),
        widget=forms.PasswordInput(attrs=attrs_dict),
        help_text=_("Enter the same password as above, for verification."))

    security_level = forms.ChoiceField(initial="user",
                                       choices=(
                                           ('user', _('User')),
                                           ('staff', _('Staff')),
                                           ('superuser', _('Superuser')),
                                       ))
    interactive = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Interactive'),
                                        (0, _('Not Interactive (no login)')),
                                    ))

    language = forms.ChoiceField(initial="en",
                                 choices=get_languages_with_local_name())

    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    class Meta:
        model = Profile
        fields = (
            'salutation',
            'first_name',
            'last_name',
            'username',
            'password1',
            'password2',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'email',
            'email2',
            'company',
            'position_title',
            'position_assignment',
            'display_name',
            'hide_in_search',
            'hide_phone',
            'hide_email',
            'hide_address',
            'initials',
            'sex',
            'mailing_name',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'county',
            'country',
            'address_2',
            'address2_2',
            'city_2',
            'state_2',
            'zipcode_2',
            'county_2',
            'country_2',
            'url',
            'dob',
            'ssn',
            'spouse',
            'time_zone',
            'language',
            'department',
            'education',
            'student',
            'direct_mail',
            'notes',
            'interactive',
            'allow_anonymous_view',
            'admin_notes',
            'security_level',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(ProfileAdminForm, self).__init__(*args, **kwargs)

        if self.instance.id:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name
            self.fields['username'].initial = self.instance.user.username
            self.fields['email'].initial = self.instance.user.email

            self.fields['password1'].required = False
            self.fields['password2'].required = False
            self.fields['password1'].widget.attrs['readonly'] = True
            self.fields['password2'].widget.attrs['readonly'] = True

            if self.instance.user.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.instance.user.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.instance.user.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.

        """
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
            if self.instance.id and user.id == self.instance.user.id:
                return self.cleaned_data['username']
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.

        """
        if not self.instance.id:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, *args, **kwargs):
        """
        Create a new user then create the user profile
        """
        request = kwargs.pop('request', None)
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        params = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
        }

        if not self.instance.id:
            password = self.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            self.instance.user = new_user
            update_user(new_user, **params)
        else:
            self.instance.old_email = self.instance.user.email

            params.update({'username': username})
            update_user(self.instance.user, **params)

        if not (request.user == self.instance.user
                and request.user.is_superuser):
            security_level = self.cleaned_data['security_level']
            if security_level == 'superuser':
                self.instance.user.is_superuser = 1
                self.instance.user.is_staff = 1
            elif security_level == 'staff':
                self.instance.user.is_superuser = 0
                self.instance.user.is_staff = 1
            else:
                self.instance.user.is_superuser = 0
                self.instance.user.is_staff = 0

            interactive = self.cleaned_data['interactive']
            try:
                interactive = int(interactive)
            except:
                interactive = 0
            self.instance.user.is_active = interactive

        if not self.instance.id:
            self.instance.creator = request.user
            self.instance.creator_username = request.user.username
        self.instance.owner = request.user
        self.instance.owner_username = request.user.username

        self.instance.user.save()
        self.instance.save()

        return super(ProfileAdminForm, self).save(*args, **kwargs)