Ejemplo n.º 1
0
class SiteBulkEditForm(BootstrapMixin, AddRemoveTagsForm,
                       CustomFieldModelBulkEditForm):
    pk = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
                                        widget=forms.MultipleHiddenInput)
    status = forms.ChoiceField(choices=add_blank_choice(SiteStatusChoices),
                               required=False,
                               initial='',
                               widget=StaticSelect())
    region = DynamicModelChoiceField(queryset=Region.objects.all(),
                                     required=False)
    group = DynamicModelChoiceField(queryset=SiteGroup.objects.all(),
                                    required=False)
    tenant = DynamicModelChoiceField(queryset=Tenant.objects.all(),
                                     required=False)
    asn = forms.IntegerField(min_value=BGP_ASN_MIN,
                             max_value=BGP_ASN_MAX,
                             required=False,
                             label='ASN')
    description = forms.CharField(max_length=100, required=False)
    time_zone = TimeZoneFormField(choices=add_blank_choice(
        TimeZoneFormField().choices),
                                  required=False,
                                  widget=StaticSelect())

    class Meta:
        nullable_fields = [
            'region',
            'group',
            'tenant',
            'asn',
            'description',
            'time_zone',
        ]
Ejemplo n.º 2
0
class SignUpForm(forms.Form):
    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())
    first_name = forms.CharField(max_length=128)
    last_name = forms.CharField(max_length=128)
    email = forms.EmailField(max_length=75)
    glucose_unit = forms.ModelChoiceField(Unit.objects.all(), empty_label=None, label='Unidad de Glucosa')
    time_zone = TimeZoneFormField(label='Zona Horaria')

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

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal col-xs-12 col-md-6 col-lg-5'
        self.helper.label_class = 'col-xs-4 col-md-4 col-lg-4'
        self.helper.field_class = 'col-xs-8 col-md-8 col-lg-8'

        self.helper.layout(
            Fieldset(
                'Cree su Cuenta'
                Field('username', autofocus=True),
                Field('password'),
                Field('first_name'),
                Field('email'),
                Field('glucose_unit'),
                Field('time_zone'),
            ),
            FormActions(
                Submit('submit', 'Crear mi cuenta',
                       css_class = 'btn-success pull-right'),
            ),
        )
Ejemplo n.º 3
0
class TestFormInvalidChoice(forms.Form):
    tz = TimeZoneFormField(
        choices=(
            [(tz, tz) for tz in pytz.all_timezones] +
            [(INVALID_TZ, pytz.UTC)]
        )
    )
Ejemplo n.º 4
0
class SignUpForm(forms.Form):
    username = forms.CharField(max_length=30,
                               validators=[validate_username_unique])
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())
    email = forms.EmailField(max_length=75, validators=[validate_email_unique])
    glucose_unit = forms.ModelChoiceField(Unit.objects.all(), empty_label=None,
                                          label='Glucose Unit')
    time_zone = TimeZoneFormField(label='Time Zone')

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

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal col-xs-12 col-md-6 col-lg-5'
        self.helper.label_class = 'col-xs-4 col-md-4 col-lg-4'
        self.helper.field_class = 'col-xs-8 col-md-8 col-lg-8'

        self. helper.layout = Layout(
            Fieldset(
                'Create Your Account',
                Field('username', autofocus=True),
                Field('password'),
                Field('email'),
                Field('glucose_unit'),
                Field('time_zone'),
            ),
            FormActions(
                Submit('submit', 'Create My Account',
                       css_class='btn-success pull-right'),
            ),
        )
Ejemplo n.º 5
0
class OrgForm(forms.ModelForm):
    language = forms.ChoiceField(required=False,
                                 choices=[("", "")] + list(settings.LANGUAGES))
    timezone = TimeZoneFormField()

    def __init__(self, *args, **kwargs):
        super(OrgForm, self).__init__(*args, **kwargs)
        if "administrators" in self.fields:
            administrators = User.objects.exclude(
                username__in=["root", "root2"])
            administrators = administrators.exclude(pk__lt=0)
            self.fields["administrators"].queryset = administrators

    def clean_domain(self):
        domain = self.cleaned_data["domain"] or ""
        domain = domain.strip().lower()

        if domain:
            if domain == getattr(settings, "HOSTNAME", ""):
                raise forms.ValidationError(
                    _("This domain is used for subdomains"))
            return domain
        else:
            return None

    class Meta:
        fields = forms.ALL_FIELDS
        model = Org
Ejemplo n.º 6
0
class UserProfileForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    org = forms.CharField(label="Organization", max_length=127, required=False)
    dept = forms.CharField(label="Department", max_length=127, required=False)
    email_announcements = forms.BooleanField(required=False)
    timezone = TimeZoneFormField()
Ejemplo n.º 7
0
class UserProfileForm(ModalForm):
    email = CharField(required=True)
    name = CharField(label='Name')
    timezone = TimeZoneFormField()

    class Meta:
        model = _user
        fields = ['email', 'name', 'timezone']
Ejemplo n.º 8
0
class OrgEditForm(forms.ModelForm):
    """
    Form for org admins to update their own org
    """
    name = forms.CharField(label=_("Organization"),
                           help_text=_("The name of this organization"))

    timezone = TimeZoneFormField(
        help_text=_("The timezone your organization is in"))

    banner_text = forms.CharField(
        label=_("Banner text"),
        widget=forms.Textarea,
        help_text=_("Banner text displayed to all users"),
        required=False)

    contact_fields = forms.MultipleChoiceField(
        choices=(),
        label=_("Contact fields"),
        help_text=_("Contact fields to display"),
        required=False)

    suspend_groups = forms.MultipleChoiceField(
        choices=(),
        label=_("Suspend groups"),
        help_text=_("Groups to remove contacts from when creating cases"),
        required=False)

    def __init__(self, *args, **kwargs):
        org = kwargs.pop('org')
        super(OrgEditForm, self).__init__(*args, **kwargs)

        self.fields['banner_text'].initial = org.get_banner_text()

        field_choices = []
        for field in Field.objects.filter(org=org,
                                          is_active=True).order_by('label'):
            field_choices.append(
                (field.pk, "%s (%s)" % (field.label, field.key)))

        self.fields['contact_fields'].choices = field_choices
        self.fields['contact_fields'].initial = [
            f.pk for f in Field.get_all(org, visible=True)
        ]

        group_choices = []
        for group in Group.get_all(org, dynamic=False).order_by('name'):
            group_choices.append((group.pk, group.name))

        self.fields['suspend_groups'].choices = group_choices
        self.fields['suspend_groups'].initial = [
            g.pk for g in Group.get_suspend_from(org)
        ]

    class Meta:
        model = Org
        fields = ('name', 'timezone', 'banner_text', 'contact_fields',
                  'suspend_groups', 'logo')
Ejemplo n.º 9
0
class UserPrefsForm(forms.ModelForm):
    time_zone = TimeZoneFormField()

    class Meta:
        model = UserPrefs
        fields = ('first_name', 'last_name', 'gender', 'birth_year',
                  'birth_month', 'birth_day', 'ethnicity', 'height_feet',
                  'height_inches', 'weight', 'determination', 'time_zone',
                  'date_format')
Ejemplo n.º 10
0
class ProfileForm(forms.Form):
    timezone = TimeZoneFormField(label='Timezone', initial='UTC')
    alert_method = forms.ChoiceField(
        label='Alert method',
        widget=forms.RadioSelect,
        choices=User.ALERT_METHOD_CHOICES,
    )
    email = forms.EmailField(label='Email address', required=False)
    full_phone = PhoneNumberField(label='Phone number', required=False)
    alert_buffer = forms.IntegerField()
Ejemplo n.º 11
0
class ProfileSignUpForm(UserCreationForm):
    """A form to register a new user."""
    location = forms.ChoiceField(choices=countries,
                                 initial='CA',)
    timezone = TimeZoneFormField(initial='Canada/Pacific')

    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', 'email', 'location',
                  'timezone')
Ejemplo n.º 12
0
class ChatUserCreationForm(UserCreationForm):

    timezone = TimeZoneFormField(choices_display="WITH_GMT_OFFSET")

    def clean(self):
        cleaned_data = super().clean()
        if len(cleaned_data['username']) < 3:
            raise ValidationError(
                "Usernames must contain 3 or more characters.")
        return cleaned_data
Ejemplo n.º 13
0
class ProfileSignUpForm(UserCreationForm):

    location = forms.CharField(max_length=30)
    timezone = TimeZoneFormField(initial='Canada/Pacific')
    bio = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email',
                    'bio', 'location', 'timezone')
Ejemplo n.º 14
0
class InviteConsumeForm(UserCreationForm):
    timezone = TimeZoneFormField(choices=TIMEZONE_CHOICES)

    class Meta(object):
        model = User
        fields = [
            "first_name", "last_name", "timezone", "password1", "password2"
        ]

    def __init__(self, *args, **kwargs):
        super(InviteConsumeForm, self).__init__(*args, **kwargs)
        self.fields["first_name"].required = True
        self.fields["last_name"].required = True
Ejemplo n.º 15
0
class OrgForm(forms.ModelForm):
    language = forms.ChoiceField(required=False,
                                 choices=[('', '')] + list(settings.LANGUAGES))
    timezone = TimeZoneFormField()

    def __init__(self, *args, **kwargs):
        super(OrgForm, self).__init__(*args, **kwargs)
        if 'administrators' in self.fields:
            administrators = User.objects.exclude(
                username__in=['root', 'root2'])
            administrators = administrators.exclude(pk__lt=0)
            self.fields['administrators'].queryset = administrators

        # Filter countries
        self.fields['country'].queryset = Org.objects.filter(
            country__isnull=True, state__isnull=True)

        # Filter states
        self.fields['state'].queryset = Org.objects.filter(
            state__isnull=True, country__isnull=False)

    def clean_domain(self):
        domain = self.cleaned_data['domain'] or ""
        domain = domain.strip().lower()

        if domain:
            if domain == getattr(settings, 'HOSTNAME', ""):
                raise forms.ValidationError(
                    _("This domain is used for subdomains"))
            return domain
        else:
            return None

    def clean(self):
        country = self.cleaned_data['country']
        state = self.cleaned_data['state']

        if country and state:
            raise forms.ValidationError(
                _("You cannot select country and state at same time."))
        return self.cleaned_data

    class Meta:
        fields = forms.ALL_FIELDS
        model = Org
Ejemplo n.º 16
0
class LeaveCreationForm(forms.ModelForm):
    timezone = TimeZoneFormField()

    class Meta:
        model = Leave
        fields = [
            'name', 'desc', 'location', 'type', 'country', 'laws', 'startdate',
            'starttime', 'enddate', 'endtime', 'timezone', 'rounds'
        ]
        exclude = [
            'user', 'hrcomments', 'status', 'is_approved', 'updated', 'created'
        ]

    def clean_enddate(self):
        enddate = self.cleaned_data['enddate']
        startdate = self.cleaned_data['startdate']
        today_date = datetime.date.today()
        return enddate
Ejemplo n.º 17
0
class SignupForm(forms.Form):
    toc = forms.BooleanField(label='Do you agree to our terms of service?')
    timezone = TimeZoneFormField()

    def signup(self, request, user):
        social_account = request.session.get('socialaccount_sociallogin')
        account = social_account.pop('account')
        user.username = "******" + account['uid']
        user.save()
        settings = AccountSettings()
        settings.user = user
        settings.tier = '1'
        settings.timezone = self.cleaned_data['timezone']
        settings.toc = self.cleaned_data['toc']
        settings.sms_daily = '0'
        settings.email_daily = '1'
        settings.save()
        Upgrade.objects.create(user=user, start_date=date.today(), expire_date=timedelta(days=365 * 99) + date.today(),
                               tier='1')
Ejemplo n.º 18
0
class ProfileForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)

        user_preferences = user_preferences_model.get_preferences(
            user_id=self.user.id)
        user_timezone = user_preferences.get('timezone', 'UTC')

        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['timezone'].widget.attrs.update({
            'select2-dropdown': '',
            'data-size': 360
        })

        self.fields['timezone'].initial = user_timezone
        self.fields['email'].initial = self.user.email

    email = forms.EmailField(
        required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'}))
    timezone = TimeZoneFormField()

    # Check email uniqueness
    def clean_email(self):
        email = self.cleaned_data.get('email')

        if email:
            if self.user.email != email:
                unique = User.objects.filter(email__iexact=email).count()

                if unique > 0:
                    raise forms.ValidationError(
                        u'An user with this email address already exists.')

        return email

    def save(self):
        data = {'timezone': str(self.cleaned_data['timezone'])}

        user_preferences_model.save_preferences(user_id=self.user.id,
                                                data=data)

        self.user.email = self.cleaned_data['email']
        self.user.save()
Ejemplo n.º 19
0
class OrgForm(forms.ModelForm):
    """
    Form for superusers to create and update orgs
    """

    language = forms.ChoiceField(required=False, choices=[("", "")] + list(settings.LANGUAGES))

    timezone = TimeZoneFormField()

    administrators = forms.ModelMultipleChoiceField(queryset=User.objects.none(), required=False)

    def __init__(self, *args, **kwargs):
        super(OrgForm, self).__init__(*args, **kwargs)
        administrators = User.objects.exclude(profile=None).order_by("profile__full_name")

        self.fields["administrators"].queryset = administrators

    class Meta:
        model = Org
        fields = forms.ALL_FIELDS
Ejemplo n.º 20
0
class TestChoicesDisplayForm(forms.Form):
    limited_tzs = [
        'Asia/Tokyo',
        'Asia/Dubai',
        'America/Argentina/Buenos_Aires',
        'Africa/Nairobi',
    ]
    limited_choices = [(tz, tz) for tz in limited_tzs]

    tz_none = TimeZoneFormField()
    tz_standard = TimeZoneFormField(choices_display='STANDARD')
    tz_with_gmt_offset = TimeZoneFormField(choices_display='WITH_GMT_OFFSET')
    tz_limited_none = TimeZoneFormField(choices=limited_choices)
    tz_limited_standard = TimeZoneFormField(choices=limited_choices,
                                            choices_display='STANDARD')
    tz_limited_with_gmt_offset = TimeZoneFormField(
        choices=limited_choices,
        choices_display='WITH_GMT_OFFSET',
    )
Ejemplo n.º 21
0
    def __init__(self, *args, **kwargs):
        super(GeneralSettingsForm, self).__init__(*args, **kwargs)

        self.profile = UserProfile.objects.get_or_create(user=self.instance)[0] if self.instance else None
        tz = self.profile.timezone if self.instance else None
        self.fields['timezone'] = TimeZoneFormField(initial=tz)
Ejemplo n.º 22
0
class UserSettingsForm(forms.Form):
    """
    Form to allow users to change profile settings and preferences.
    """
    username = forms.CharField(required=False)
    first_name = forms.CharField(label='First Name', required=False)
    last_name = forms.CharField(label='Last Name', required=False)
    email = forms.EmailField(label='Email', required=False)
    time_zone = TimeZoneFormField(label='Time Zone')

    glucose_unit = forms.ModelChoiceField(
        Unit.objects.all(), label='Glucose Unit', empty_label=None)
    default_category = forms.ModelChoiceField(
        Category.objects.all(), label='Default Category',
        empty_label='Auto', required=False)

    glucose_low = forms.DecimalField(
        label='Low', max_digits=6, max_value=3000, min_value=0,
        help_text="Below this value is a low blood glucose."
    )
    glucose_high = forms.DecimalField(
        label='High', max_digits=6, max_value=3000, min_value=0,
        help_text="Above this value is a high blood glucose."
    )
    glucose_target_min = forms.DecimalField(
        label='Target Min', max_digits=6, max_value=3000, min_value=0,
        help_text="Your target range's minimum value."
    )
    glucose_target_max = forms.DecimalField(
        label='Target Max', max_digits=6, max_value=3000, min_value=0,
        help_text="Your target range's maximum value."
    )

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

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal col-xs-12 col-md-6 col-lg-6'
        self.helper.label_class = 'col-xs-4 col-md-4 col-lg-4'
        self.helper.field_class = 'col-xs-8 col-md-8 col-lg-8'
        self.helper.help_text_inline = False

        self. helper.layout = Layout(
            HTML('''
            {% if messages %}
            {% for message in messages %}
            <p {% if message.tags %} class="alert alert-{{ message.tags }}"\
            {% endif %}>{{ message }}</p>{% endfor %}{% endif %}
            </p>
            '''),
            Fieldset(
                'Profile',
                Field('username', readonly=True),
                Field('email'),
                Field('first_name'),
                Field('last_name'),
                Field('time_zone'),
            ),
            Fieldset(
                'Preferences',
                Field('glucose_unit'),
                Field('default_category'),
            ),
            Fieldset(
                'Glucose Levels',
                Field('glucose_low'),
                Field('glucose_high'),
                Field('glucose_target_min'),
                Field('glucose_target_max'),
            ),
            FormActions(
                Submit('submit', 'Save'),
                Button('cancel', 'Cancel',
                       onclick='location.href="%s";' \
                       % reverse('dashboard')),
            ),
        )

    def clean_email(self):
        """
        Validates the email field.

        Check if the email field changed. If true, check whether the new email
        address already exists in the database and raise an error if it does.
        """
        email = self.cleaned_data['email']
        user = User.objects.get(username=self.cleaned_data['username'])

        if email != user.email:
            if User.objects.filter(email__iexact=email):
                raise forms.ValidationError('Another account is already using '
                                            'this email address.')

        return email
Ejemplo n.º 23
0
class UserTimeZoneForm(forms.Form):
    timezone = TimeZoneFormField(help_text="Enter your correct timezone")
Ejemplo n.º 24
0
class SiteForm(TenancyForm, CustomFieldModelForm):
    region = DynamicModelChoiceField(queryset=Region.objects.all(),
                                     required=False)
    group = DynamicModelChoiceField(queryset=SiteGroup.objects.all(),
                                    required=False)
    asns = DynamicModelMultipleChoiceField(queryset=ASN.objects.all(),
                                           label=_('ASNs'),
                                           required=False)
    slug = SlugField()
    time_zone = TimeZoneFormField(choices=add_blank_choice(
        TimeZoneFormField().choices),
                                  required=False,
                                  widget=StaticSelect())
    comments = CommentField()
    tags = DynamicModelMultipleChoiceField(queryset=Tag.objects.all(),
                                           required=False)

    class Meta:
        model = Site
        fields = [
            'name',
            'slug',
            'status',
            'region',
            'group',
            'tenant_group',
            'tenant',
            'facility',
            'asn',
            'asns',
            'time_zone',
            'description',
            'physical_address',
            'shipping_address',
            'latitude',
            'longitude',
            'contact_name',
            'contact_phone',
            'contact_email',
            'comments',
            'tags',
        ]
        fieldsets = (
            ('Site', (
                'name',
                'slug',
                'status',
                'region',
                'group',
                'facility',
                'asn',
                'asns',
                'time_zone',
                'description',
                'tags',
            )),
            ('Tenancy', ('tenant_group', 'tenant')),
            ('Contact Info', (
                'physical_address',
                'shipping_address',
                'latitude',
                'longitude',
                'contact_name',
                'contact_phone',
                'contact_email',
            )),
        )
        widgets = {
            'physical_address': SmallTextarea(attrs={
                'rows': 3,
            }),
            'shipping_address': SmallTextarea(attrs={
                'rows': 3,
            }),
            'status': StaticSelect(),
            'time_zone': StaticSelect(),
        }
        help_texts = {
            'name': "Full name of the site",
            'asn':
            "BGP autonomous system number.  This field is depreciated in favour of the ASN model",
            'facility': "Data center provider and facility (e.g. Equinix NY7)",
            'time_zone': "Local time zone",
            'description': "Short description (will appear in sites list)",
            'physical_address':
            "Physical location of the building (e.g. for GPS)",
            'shipping_address': "If different from the physical address",
            'latitude': "Latitude in decimal format (xx.yyyyyy)",
            'longitude': "Longitude in decimal format (xx.yyyyyy)"
        }
Ejemplo n.º 25
0
class UserCreateEditForm(forms.ModelForm):

    error_messages = {
        'duplicate_username': _("A user with that user name already exists."),
        'duplicate_email': _("A user with that email already exists."),
        'password_mismatch': _("The two password fields didn't match."),
        'email_mismatch': _("The two email fields didn't match."),
        'invalid_current_password': _("Your current password is incorrect."),
        'invalid_char':
        _("May only contain the characters A-Z, 0-9, '-' and ' '."),
        'invalid_page_size': _("May only contain the characters 0-9"),
        'invalid_offset': _("Invalid UTC offset value"),
    }

    is_active = forms.BooleanField(
        label=_('Active'),
        widget=forms.CheckboxInput(attrs={'class': 'custom-control-input'}),
        help_text=_("User will not be able to login if disabled"),
        required=False)

    username = forms.CharField(
        label=_('User Name'),
        required=False,
        validators=[
            MinLengthValidator(3),
            MaxLengthValidator(150),
        ],
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': _('User name'),
                'pattern': '.{3,150}',
                'required': '1'
            }),
        help_text=_("Username must at least 3 characters"),
    )

    first_name = forms.CharField(
        label=_('First Name'),
        required=False,
        validators=[
            MinLengthValidator(3),
            MaxLengthValidator(30),
        ],
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': _('First Name'),
                'pattern': '.{0,30}'
            }),
        help_text=_("Maximum 30 characters"),
    )

    last_name = forms.CharField(
        label=_('Last Name'),
        required=False,
        validators=[
            MinLengthValidator(3),
            MaxLengthValidator(30),
        ],
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': _('Last Name'),
                'pattern': '.{0,30}'
            }),
        help_text=_("Maximum 30 characters"),
    )

    email = forms.EmailField(
        label=_('Email Address'),
        required=False,
        error_messages={'required': _('Enter a valid email address.')},
        widget=forms.EmailInput(attrs={
            'class': 'form-control email',
            'placeholder': _('Email address')
        }),
    )

    password = forms.CharField(
        label=_('Password'),
        required=False,
        validators=[MinLengthValidator(8)],
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control password',
                'placeholder': _('Password'),
                'required': '1'
            }),
    )

    oauth_scope = forms.ChoiceField(
        label=_("Permissions"),
        choices=ROLE_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control'}),
        required=False,
        validators=[
            RegexValidator(r'^[a-zA-Z0-9- ]*$',
                           message=error_messages['invalid_char'],
                           code='invalid_char'),
            MaxLengthValidator(255),
            MinLengthValidator(4),
        ],
    )

    timezone = TimeZoneFormField(
        label=UserProfile._meta.get_field('timezone').verbose_name,
        help_text=_(
            'Select your preferred timezone or location within the timezone.'),
        widget=forms.Select(attrs={'class': 'form-control'}),
    )

    page_size = forms.ChoiceField(
        label=_("Results Per Page"),
        choices=PAGE_SIZE_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control'}),
        required=False,
        validators=[
            RegexValidator(r'^[0-9]*$',
                           message=error_messages['invalid_page_size'],
                           code='invalid_page_size'),
        ],
    )

    api_access = forms.BooleanField(
        label=_('API Access'),
        widget=forms.CheckboxInput(attrs={'class': 'custom-control-input'}),
        required=False)

    api_code = forms.ChoiceField(
        label=_("API Auth Token"),
        choices=ROLE_CHOICES,
        widget=None,
        required=False,
    )

    class Meta:
        model = User
        fields = ('is_active', 'username', 'first_name', 'last_name', 'email',
                  'password', 'oauth_scope', 'page_size', 'api_access',
                  'api_code', 'timezone')
Ejemplo n.º 26
0
class OrgEditForm(forms.ModelForm):
    """
    Form for org admins to update their own org
    """

    name = forms.CharField(label=_("Organization"), help_text=_("The name of this organization"))

    timezone = TimeZoneFormField(help_text=_("The timezone your organization is in"))

    banner_text = forms.CharField(
        label=_("Banner text"),
        widget=forms.Textarea,
        help_text=_("Banner text displayed to all users"),
        required=False,
    )

    contact_fields = forms.MultipleChoiceField(
        choices=(), label=_("Contact fields"), help_text=_("Contact fields to display"), required=False
    )

    suspend_groups = forms.MultipleChoiceField(
        choices=(),
        label=_("Suspend groups"),
        help_text=_("Groups to remove contacts from when creating cases"),
        required=False,
    )

    followup_flow = forms.ChoiceField(
        choices=(), label=_("Follow-up Flow"), help_text=_("Flow to start after a case is closed"), required=False,
    )

    def __init__(self, *args, **kwargs):
        org = kwargs.pop("org")
        super(OrgEditForm, self).__init__(*args, **kwargs)

        self.fields["banner_text"].initial = org.get_banner_text()

        field_choices = []
        for field in Field.objects.filter(org=org, is_active=True).order_by("label"):
            field_choices.append((field.pk, "%s (%s)" % (field.label, field.key)))

        self.fields["contact_fields"].choices = field_choices
        self.fields["contact_fields"].initial = [f.pk for f in Field.get_all(org, visible=True)]

        group_choices = []
        for group in Group.get_all(org, dynamic=False).order_by("name"):
            group_choices.append((group.pk, group.name))

        self.fields["suspend_groups"].choices = group_choices
        self.fields["suspend_groups"].initial = [g.pk for g in Group.get_suspend_from(org)]

        flow_choices = [("", "----")]
        for flow in org.get_backend().fetch_flows(org):
            flow_choices.append((flow.uuid, flow.name))

        flow_initial = org.get_followup_flow()

        self.fields["followup_flow"].choices = flow_choices
        if flow_initial:
            self.fields["followup_flow"].initial = flow_initial.uuid

    class Meta:
        model = Org
        fields = ("name", "timezone", "banner_text", "contact_fields", "suspend_groups", "followup_flow", "logo")
Ejemplo n.º 27
0
class TimezoneForm(Form):
    timezone = TimeZoneFormField()
Ejemplo n.º 28
0
class Members(models.Model):
    member_id = models.CharField(max_length=10)
    real_name = models.CharField(max_length=30)
    tz = TimeZoneFormField()
    activity_periods = Activity_Periods
Ejemplo n.º 29
0
 def test_invalid_choices_display(self):
     self.assertRaises(ValueError,
                       lambda: TimeZoneFormField(choices_display='invalid'))
Ejemplo n.º 30
0
class TestForm(forms.Form):
    tz = TimeZoneFormField()
    tz_opt = TimeZoneFormField(required=False)