Ejemplo n.º 1
0
class SuperuserManagementForm(forms.Form):
    csv_email_list = forms.CharField(
        label="Comma seperated email addresses",
        widget=forms.Textarea()
    )
    privileges = forms.MultipleChoiceField(
        choices=[
            ('is_superuser', 'Mark as superuser'),
        ],
        widget=forms.CheckboxSelectMultiple(),
        required=False,
    )

    def clean(self):
        from email.utils import parseaddr
        from django.contrib.auth.models import User
        csv_email_list = self.cleaned_data.get('csv_email_list', '')
        csv_email_list = csv_email_list.split(',')
        csv_email_list = [parseaddr(em)[1] for em in csv_email_list]
        if len(csv_email_list) > 10:
            raise forms.ValidationError(
                "This command is intended to grant superuser access to few users at a time. "
                "If you trying to update permissions for large number of users consider doing it via Django Admin"
            )

        users = []
        for username in csv_email_list:
            if "@dimagi.com" not in username:
                raise forms.ValidationError(u"Email address '{}' is not a dimagi email address".format(username))
            try:
                users.append(User.objects.get(username=username))
            except User.DoesNotExist:
                raise forms.ValidationError(
                    u"User with email address '{}' does not exist on "
                    "this site, please have the user registered first".format(username))

        self.cleaned_data['users'] = users
        return self.cleaned_data

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

        if can_toggle_is_staff:
            self.fields['privileges'].choices.append(
                ('is_staff', 'mark as developer')
            )

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.layout = crispy.Layout(
            'csv_email_list',
            'privileges',
            FormActions(
                crispy.Submit(
                    'superuser_management',
                    'Update privileges'
                )
            )
        )
Ejemplo n.º 2
0
 def __init__(self, form, request, formentry_model=FormEntry,
              fieldentry_model=FieldEntry, *args, **kwargs):
     """
     Iterate through the fields of the ``forms.models.Form`` instance and
     create the form fields required to control including the field in
     the export (with a checkbox) or filtering the field which differs
     across field types. User a list of checkboxes when a fixed set of
     choices can be chosen from, a pair of date fields for date ranges,
     and for all other types provide a textbox for text search.
     """
     self.form = form
     self.request = request
     self.formentry_model = formentry_model
     self.fieldentry_model = fieldentry_model
     self.form_fields = form.fields.all()
     self.entry_time_name = unicode(self.formentry_model._meta.get_field(
         "entry_time").verbose_name).encode("utf-8")
     super(EntriesForm, self).__init__(*args, **kwargs)
     for field in self.form_fields:
         field_key = "field_%s" % field.id
         # Checkbox for including in export.
         self.fields["%s_export" % field_key] = forms.BooleanField(
             label=field.label, initial=True, required=False)
         if field.is_a(*fields.CHOICES):
             # A fixed set of choices to filter by.
             if field.is_a(fields.CHECKBOX):
                 choices = ((True, _("Checked")), (False, _("Not checked")))
             else:
                 choices = field.get_choices()
             contains_field = forms.MultipleChoiceField(label=" ",
                 choices=choices, widget=forms.CheckboxSelectMultiple(),
                 required=False)
             self.fields["%s_filter" % field_key] = choice_filter_field
             self.fields["%s_contains" % field_key] = contains_field
         elif field.is_a(*fields.MULTIPLE):
             # A fixed set of choices to filter by, with multiple
             # possible values in the entry field.
             contains_field = forms.MultipleChoiceField(label=" ",
                 choices=field.get_choices(),
                 widget=forms.CheckboxSelectMultiple(),
                 required=False)
             self.fields["%s_filter" % field_key] = multiple_filter_field
             self.fields["%s_contains" % field_key] = contains_field
         elif field.is_a(*fields.DATES):
             # A date range to filter by.
             self.fields["%s_filter" % field_key] = date_filter_field
             self.fields["%s_from" % field_key] = forms.DateField(
                 label=" ", widget=SelectDateWidget(), required=False)
             self.fields["%s_to" % field_key] = forms.DateField(
                 label=_("and"), widget=SelectDateWidget(), required=False)
         else:
             # Text box for search term to filter by.
             contains_field = forms.CharField(label=" ", required=False)
             self.fields["%s_filter" % field_key] = text_filter_field
             self.fields["%s_contains" % field_key] = contains_field
     # Add ``FormEntry.entry_time`` as a field.
     field_key = "field_0"
     label = self.formentry_model._meta.get_field("entry_time").verbose_name
     self.fields["%s_export" % field_key] = forms.BooleanField(
         initial=True, label=label, required=False)
     self.fields["%s_filter" % field_key] = date_filter_field
     self.fields["%s_from" % field_key] = forms.DateField(
         label=" ", widget=SelectDateWidget(), required=False)
     self.fields["%s_to" % field_key] = forms.DateField(
         label=_("and"), widget=SelectDateWidget(), required=False)
Ejemplo n.º 3
0
class CourseForm(forms.ModelForm):
    course_days = forms.MultipleChoiceField(
        choices=Course.DAYS,
        label='Class days (select all that apply)',
        widget=forms.CheckboxSelectMultiple(
            attrs={'class': 'mb-2 list-unstyled'}))

    class Meta:
        model = Course
        fields = ('course_name', 'course_days', 'start_time', 'end_time',
                  'instructor')
        labels = {
            'course_name':
            'Class name',
            'start_time':
            'Start time (e.g. 10:00 AM)',
            'end_time':
            'End time (e.g. 12:00 PM)',
            'instructor':
            'Instructor (not selecting will be set to '
            '\'Not Specified\')'
        }
        widgets = {
            'course_name':
            TextInput(attrs={'class': 'form-control mb-2'}),
            'start_time':
            TimeInput(format='%H:%M',
                      attrs={
                          'class': 'form-control mb-2',
                          'type': 'time'
                      }),
            'end_time':
            TimeInput(format='%H:%M',
                      attrs={
                          'class': 'form-control mb-2',
                          'type': 'time'
                      }),
            'instructor':
            Select(attrs={'class': 'form-control mb-2'})
        }
        required = {
            'instructor': False,
        }

    def __init__(self, *args, **kwargs):
        aca_id = kwargs.pop('aca_id')
        super().__init__(*args, **kwargs)
        # Show only current academy's instructors as an option
        self.fields['instructor'].queryset = Member.objects.filter(
            mem_type=Member.INST, aca_id=aca_id)

    def clean_course_days(self):
        """
        Formats course_days e.g. ['M', 'W', 'F'] -> M/W/F before saving.
        :return:
        """
        # Format course days
        course_days = self.cleaned_data['course_days']
        formatted_days = ''
        for day in course_days:
            formatted_days += day + '/'
        # Remove the last '/' ch
        return formatted_days[0:len(formatted_days) - 1]
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        event = self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)

        recp_choices = [
            ('orders', _('Everyone who created a ticket order'))
        ]
        if event.settings.attendee_emails_asked:
            recp_choices += [
                ('attendees', _('Every attendee (falling back to the order contact when no attendee email address is '
                                'given)')),
                ('both', _('Both (all order contact addresses and all attendee email addresses)'))
            ]
        self.fields['recipients'].choices = recp_choices

        self.fields['subject'] = I18nFormField(
            label=_('Subject'),
            widget=I18nTextInput, required=True,
            locales=event.settings.get('locales'),
        )
        self.fields['message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea, required=True,
            locales=event.settings.get('locales'),
        )
        self._set_field_placeholders('subject', ['event', 'order', 'position_or_address'])
        self._set_field_placeholders('message', ['event', 'order', 'position_or_address'])
        choices = list(Order.STATUS_CHOICE)
        if not event.settings.get('payment_term_expire_automatically', as_type=bool):
            choices.append(
                ('overdue', _('pending with payment overdue'))
            )
        self.fields['sendto'] = forms.MultipleChoiceField(
            label=_("Send to customers with order status"),
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'scrolling-multiple-choice'}
            ),
            choices=choices
        )
        if not self.initial.get('sendto'):
            self.initial['sendto'] = ['p', 'n']

        self.fields['items'].queryset = event.items.all()
        if not self.initial.get('items'):
            self.initial['items'] = event.items.all()

        self.fields['checkin_lists'].queryset = event.checkin_lists.all()
        self.fields['checkin_lists'].widget = Select2Multiple(
            attrs={
                'data-model-select2': 'generic',
                'data-select2-url': reverse('control:event.orders.checkinlists.select2', kwargs={
                    'event': event.slug,
                    'organizer': event.organizer.slug,
                }),
                'data-placeholder': _('Send to customers checked in on list'),
            }
        )
        self.fields['checkin_lists'].widget.choices = self.fields['checkin_lists'].choices
        self.fields['checkin_lists'].label = _('Send to customers checked in on list')

        if event.has_subevents:
            self.fields['subevent'].queryset = event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2': 'event',
                    'data-select2-url': reverse('control:event.subevents.select2', kwargs={
                        'event': event.slug,
                        'organizer': event.organizer.slug,
                    }),
                    'data-placeholder': pgettext_lazy('subevent', 'Date')
                }
            )
            self.fields['subevent'].widget.choices = self.fields['subevent'].choices
        else:
            del self.fields['subevent']
Ejemplo n.º 5
0
class EmployerAddJobListing(forms.ModelForm):
    CONTRACT_TYPE = (
        ("1", "Temporary"),
        ("2", "Contract"),
        ("3", "Internship"),
        ("4", "Commission"),
        ("5", "New Grad"),
        ("6", "Permanent"),
    )

    YES_NO = (
        ("true", "YES"),
        ("false", "NO"),
    )

    NO_YES = (
        ("false", "NO"),
        ("true", "YES"),
    )

    SCHEDULES = (
        ("8 hour shift", "8 hour shift"),
        ("10 hour shift", "10 hour shift"),
        ("12 hour shift", "12 hour shift"),
        ("Shift system", "Shift system"),
        ("Early shift", "Early shift"),
        ("Day shift", "Day shift"),
        ("Afternoon shift", "Afternoon shift"),
        ("Evening shift", "Evening shift"),
        ("Late shift", "Late shift"),
        ("Night shift", "Night shift"),
        ("Flexible shift", "Flexible shift"),
        ("Rotational shift", "Rotational shift"),
        ("Monday to Friday", "Monday to Friday"),
        ("Holidays", "Holidays"),
        ("Weekends", "Weekends"),
        ("Overtime", "Overtime"),
        ("On call", "On call"),
        ("Others", "Others"),
    )

    COMPENSATION_RANGE = (
        ("Range", "Range"),
        ("Starting at", "Starting at"),
        ("Up to", "Up to"),
        ("Exact Rate", "Exact Rate"),
    )

    DEMO_CHOICES = (("Sample", "Sample"), )

    HANDICAPPED_TYPES = (
        ("Blind", "Blind"),
        ("Legally Blind", "Legally Blind"),
        ("Locomotor Disability (Hands)", "Locomotor Disability (Hands)"),
        ("Locomotor Disability (Feet/Legs)",
         "Locomotor Disability (Feet/Legs)"),
        ("Hearing Impairment", "Hearing Impairment"),
        ("Speech and Language Disability", "Speech and Language Disability"),
        ("Intellectual Disability", "Intellectual Disability"),
    )

    SUPPLEMENTAL_PAY = (
        ("13th month salary", "13th month salary"),
        ("Overtime pay", "Overtime pay"),
        ("Commission pay", "Commission pay"),
        ("Yearly bonus", "Yearly bonus"),
        ("Bonus pay", "Bonus pay"),
        ("Performance bonus", "Performance bonus"),
        ("Tips", "Tips"),
        ("Quarterly bonus", "Quarterly bonus"),
        ("Anniversary bonus", "Anniversary bonus"),
        ("Other", "Other"),
        ("None", "None"),
    )

    BENEFITS = (
        ("Paid training", "Paid training"),
        ("Work from home", "Work from home"),
        ("On-site parking", "On-site parking"),
        ("Flexible schedule", "Flexible schedule"),
        ("Discounted lunch", "Discounted lunch"),
        ("Employee discount", "Employee discount"),
        ("Paid toll fees", "Paid toll fees"),
        ("Company events", "Company events"),
        ("Gym membership", "Gym membership"),
        ("Health insurance", "Health insurance"),
        ("Additional leave", "Additional leave"),
        ("Free parking", "Free parking"),
        ("Company car", "Company car"),
        ("Company Christmas gift", "Company Christmas gift"),
        ("Life insurance", "Life insurance"),
        ("Fuel discount", "Fuel discount"),
        ("Employee stock ownership plan", "Employee stock ownership plan"),
        ("Others", "Others"),
        ("Christmas Bonus", "Christmas Bonus"),
        ("None", "None"),
    )

    APPLICATION_TYPE = (
        ("Email", "Email"),
        ("In-Person", "In-Person"),
    )

    REQUIRED_QUALIFICATION = (
        ("Required", "Required"),
        ("Preferred", "Preferred"),
    )

    EMPLOYMENT_TYPE = (
        ("Full-time Job", "Full-time Job"),
        ("Part-time Job", "Part-time Job"),
    )

    CHOICES = [('2', 'Temporarily due to COVID-19'), ('3', 'Yes'), ('1', 'No')]
    accept_handicapped = forms.ChoiceField(choices=NO_YES)
    accepted_handicapped_types = forms.MultipleChoiceField(
        choices=HANDICAPPED_TYPES,
        required=False,
        widget=forms.CheckboxSelectMultiple(attrs={'data-required': 'False'}))
    contract_type = forms.MultipleChoiceField(
        choices=CONTRACT_TYPE,
        widget=forms.CheckboxSelectMultiple(attrs={'data-required': 'True'}))
    job_schedules = forms.MultipleChoiceField(
        choices=SCHEDULES,
        widget=forms.CheckboxSelectMultiple(attrs={'data-required': 'True'}))
    date_prompt = forms.ChoiceField(choices=NO_YES)

    initial_salary = forms.DecimalField(widget=forms.NumberInput(
        attrs={'placeholder': 'From: (E.g. 10000.00)'}))
    max_salary = forms.DecimalField(
        required=False,
        widget=forms.NumberInput(attrs={'placeholder': '(E.g. 50000.00)'}))
    supplemental_pay = forms.MultipleChoiceField(
        choices=SUPPLEMENTAL_PAY,
        widget=forms.CheckboxSelectMultiple(attrs={'data-required': 'True'}))
    benefits = forms.MultipleChoiceField(
        choices=BENEFITS,
        widget=forms.CheckboxSelectMultiple(attrs={'data-required': 'True'}))
    remote = forms.ChoiceField(choices=CHOICES)
    application_type = forms.ChoiceField(choices=APPLICATION_TYPE)
    application_resume = forms.ChoiceField(choices=YES_NO)

    employment_type = forms.ChoiceField(choices=EMPLOYMENT_TYPE)

    application_deadline = forms.DateField(widget=DateInput, required=False)

    # qualification_experience_type = forms.MultipleChoiceField(choices=DEMO_CHOICES)
    # qualification_minimum_education_level = forms.MultipleChoiceField(choices=DEMO_CHOICES)
    # qualification_licenses = forms.MultipleChoiceField(choices=DEMO_CHOICES)
    # qualification_languages = forms.MultipleChoiceField(choices=DEMO_CHOICES)

    compensation_range = forms.ChoiceField(choices=COMPENSATION_RANGE)

    class Meta:
        model = models.JobListing
        exclude = ('employer', )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        #widgets
        self.fields['accept_handicapped'].widget.attrs.update({
            'class':
            'yes-no-option',
            'data-name':
            'accepted_handicapped_types'
        })
        self.fields['date_prompt'].widget.attrs.update({
            'class':
            'yes-no-option',
            'data-name':
            'start_date'
        })
        self.fields['application_resume'].widget.attrs.update({
            'class':
            'yes-no-option',
            'data-name':
            'application_deadline'
        })

        #labels
        self.fields[
            'date_prompt'].label = "Is there a planned start date for this job?"
        self.fields['initial_salary'].label = ""
        self.fields['max_salary'].label = ""
        self.fields[
            'application_type'].label = "How do you want to receive applications?"
        self.fields[
            'application_resume'].label = "Is there an application deadline?"
        self.fields[
            'application_email_recepient'].label = "Daily updates about this job and candidates will be sent to:"
        self.helper.form_id = "form-add-job"
        #self.helper.add_input(Submit('save', 'Save', css_class='experiencelevel-save-btn btn-applicant'))
        #self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-danger-dark text-white', css_id="cancel-experiencelevel-form"))
        self.helper.layout = Layout(
            Fieldset(
                '',
                Div(  #Page 1
                    Div(Div(
                        'job_title',
                        css_class='col-6',
                    ),
                        Div(
                            'location',
                            css_class='col-6',
                        ),
                        css_class='row d-flex justify-conent-center'),
                    Div(Div(
                        'remote',
                        css_class='col-6',
                    ),
                        Div(
                            'hires_needed',
                            css_class='col-6',
                        ),
                        css_class='row d-flex justify-conent-center'),
                    'accept_handicapped',
                    'accepted_handicapped_types',
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-right" data-target-page="p2-add-job">Next Page</button> """
                    ),
                    css_class='pages-add-job',
                    css_id='p1-add-job',
                ),
                Div(  #Page 2
                    'employment_type',
                    'contract_type',
                    'job_schedules',
                    'date_prompt',
                    'start_date',
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-left" data-target-page="p1-add-job">Previous Page</button> """
                    ),
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-right" data-target-page="p3-add-job">Next Page</button> """
                    ),
                    css_class='pages-add-job d-none',
                    css_id='p2-add-job',
                ),
                Div(  #Page 3
                    'compensation_range',
                    Div('initial_salary',
                        HTML(
                            ''' <span class="align-middle p-2" id="span-compensation">TO</span> '''
                        ),
                        'max_salary',
                        css_class="d-flex flex-row"),
                    'supplemental_pay',
                    'benefits',
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-left" data-target-page="p2-add-job">Previous Page</button> """
                    ),
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-right" data-target-page="p4-add-job">Next Page</button> """
                    ),
                    css_class='pages-add-job d-none',
                    css_id='p3-add-job',
                ),
                Div(  #Page 4
                    'application_type',
                    'application_resume',
                    'application_deadline',
                    'application_email_recepient',
                    'job_description',
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-left" data-target-page="p3-add-job">Previous Page</button> """
                    ),
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-right" data-target-page="p5-add-job">Next Page</button> """
                    ),
                    css_class='pages-add-job d-none',
                    css_id='p4-add-job',
                ),
                Div(  #Page 5
                    HTML("""
                        <div class="btn-group" role="group">
                            <button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Add Qualification
                            </button>
                            <div class="dropdown-menu" aria-labelledby="btnGroupDrop1" id="dropdown-add-qualification">
                                <a class="dropdown-item" href="#">Experience</a>
                                <a class="dropdown-item" href="#">Education</a>
                                <a class="dropdown-item" href="#">Location</a>
                                <a class="dropdown-item" href="#">License</a>
                                <a class="dropdown-item" href="#">Language</a>
                            </div>
                        </div>
                        
                        <div class="container " id="p5-container">
                            <div class="qualification-template d-none my-3 card-primary-theme-p5">
                                <div>
                                    <h5><span id="qualification-header">Experience</span> <i class="fas fa-times float-right pr-3 pt-2 pointer" name="card-close"></i></h5>
                                </div>
                                <hr style="background-color: white">
                                <div id="qualification-body"> 
                                    <h6>Minimum of <input type="text" class="custom-form-input m-2 p-2" name="year"> of <input type="text" class="p-2 custom-form-input m-2" name="experience">  Experience</h6>
                                </div>
                                <div id="qualification-footer">
                                    <h5>Is this qualification required?</h5>
                                    <select name="required-preferred" class="select form-control custom-select w-50" id="id_application_resume"> 
                                        <option value="true">Required</option> 
                                        <option value="false">Preferred</option>
                                    </select>
                                </div>
                            </div>
                            <div class="qualification-template my-3 card-primary-theme-p5" name="qualification-experience"> <div> <h5><span id="qualification-header">Experience</span> <i class="fas fa-times float-right pr-3 pt-2 pointer" name="card-close" aria-hidden="true"></i></h5> </div> <hr style="background-color: white"> <div id="qualification-body"> <h6>Minimum of <input type="text" class="custom-form-input m-2 p-2" name="year"> of <input type="text" class="p-2 custom-form-input m-2" name="experience">  Experience</h6> </div> <div id="qualification-footer"> <h5>Is this qualification required?</h5> <select name="required-preferred" class="select form-control custom-select w-50" id="id_application_resume"> <option value="true">Required</option> <option value="false">Preferred</option> </select> </div> </div>
                        </div>
                        
                        
                    """),
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-left" data-target-page="p4-add-job">Previous Page</button> """
                    ),
                    HTML(
                        """ <button type="button" name="" id="btn-preview-job" class="btn btn-secondary pull-right">View Preview</button> """
                    ),
                    css_class='pages-add-job d-none',
                    css_id='p5-add-job',
                ),
                Div(  #Page 6
                    HTML("""
                        <div class="job-preview card-secondary-theme" id="job-preview">

                        </div>
                    """),
                    HTML(
                        """ <button type="button" name="" id="" class="btn btn-applicant btn-move-page pull-left" data-target-page="p5-add-job">Previous Page</button> """
                    ),
                    HTML(
                        """ <button type="button" name="" id="btn-post-job" class="btn btn-secondary pull-right">Post Job</button> """
                    ),
                    css_class='pages-add-job d-none',
                    css_id='p6-add-job',
                ),
            ), )
Ejemplo n.º 6
0
 class Meta:
     model = Article
     exclude = ['editor', 'pub_date']
     widgets = {
         'tags': forms.CheckboxSelectMultiple(),
     }
Ejemplo n.º 7
0
 class Meta:
     model = ScheduleBuildingSettings
     fields = ['parameters']
     widgets = {'parameters': forms.CheckboxSelectMultiple()}
Ejemplo n.º 8
0
class MyGroupForm(forms.ModelForm):
    mobile = forms.CharField(validators=[check_for_valid_mobile_number])
    registered_events = forms.ModelMultipleChoiceField(queryset=Event.objects.filter(event_reg_type=2), widget=forms.CheckboxSelectMultiple(), required=True, error_messages={'required': 'Please select an event to register!'})
    persons = forms.CharField(widget=forms.HiddenInput(attrs={'id': 'omg'}))
    class Meta:
        model = MyGroup
        fields = "__all__"
Ejemplo n.º 9
0
 class Meta:
     model = Attendance
     fields = ['student', ]
     widgets = {'student': forms.CheckboxSelectMultiple()}
Ejemplo n.º 10
0
class ReplyMarkup(forms.Form):
    checkboxes = forms.MultipleChoiceField(
        required=False, choices=CHECKBOX_CHOICES,
        widget=forms.CheckboxSelectMultiple(
            attrs={
                'class': 'custom-control-input'
            }
        )
    )
    react_text = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'form-control mb-2 shadow-sm',
                'placeholder': 'React Text',
                'onchange': "languageDetect(this);"
            }
        )
    )
    row_width = forms.IntegerField(max_value=5, min_value=1,
                                   widget=forms.NumberInput(attrs={
                                       'class': 'form-control shadow-sm',
                                       'placeholder': 'Row Width'
                                   }))
    response_text_markup = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control shadow-sm', 'placeholder': 'Response Text'
        })
    )
    smart = forms.MultipleChoiceField(
        required=False, choices=(
            ('smart', 'Smart recognition'),
        ), widget=forms.CheckboxSelectMultiple(
            attrs={
                'class': 'custom-control-input'
            }
        )
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        self.token = kwargs.pop("token")
        super(ReplyMarkup, self).__init__(*args, **kwargs)

    def clean_react_text(self):
        new_react_text = self.cleaned_data['react_text']
        token = self.token.replace(':', '_')

        path = os.path.join(
            settings.BASE_DIR, 'BotConstructor',
            'media', 'ScriptsBots',
            f'{self.request.user.username}',
            f'{self.request.user.username}_{token}_configuration.json'
        )
        try:
            with open(path, 'r', encoding='utf-8') as file:
                object_text = json.load(file)['reply_markup']

            for item in object_text:
                if item['react_text'] == new_react_text:
                    self.add_error(
                        'react_text',
                        f'Object "{new_react_text}" has already been created')
        except KeyError as key:
            print(key)
        return new_react_text
Ejemplo n.º 11
0
class TextForm(forms.Form):
    response_text = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'form-control shadow-sm',
        'placeholder': 'Response Text',
        'style': 'height: 80px'
    }), required=True)
    react_text = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'form-control shadow-sm',
                'placeholder': 'React Text',
                'onchange': "languageDetect(this);"
            }
        ),
        required=True
    )
    remove_reply_markup = forms.MultipleChoiceField(
        required=False, choices=(
            ('remove_reply', 'Remove Reply Markup'),
        ), widget=forms.CheckboxSelectMultiple(
            attrs={
                'class': 'custom-control-input'
            }
        )
    )
    smart = forms.MultipleChoiceField(
        required=False, choices=(
            ('smart', 'Smart recognition'),
        ), widget=forms.CheckboxSelectMultiple(
            attrs={
                'class': 'custom-control-input'
            }
        )
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        self.token = kwargs.pop("token")
        super(TextForm, self).__init__(*args, **kwargs)

    def clean_react_text(self):
        new_react_text = self.cleaned_data['react_text']
        token = self.token.replace(':', '_')

        path = os.path.join(
            settings.BASE_DIR, 'BotConstructor',
            'media', 'ScriptsBots',
            f'{self.request.user.username}',
            f'{self.request.user.username}_{token}_configuration.json'
        )
        try:
            with open(path, 'r', encoding='utf-8') as file:
                object_text = json.load(file)['text']

            for item in object_text:
                if item['react_text'] == new_react_text:
                    raise forms.ValidationError(
                        f'Object "{new_react_text}" has already been created')
        except KeyError as key:
            print(key)
        return new_react_text
Ejemplo n.º 12
0
 class Meta:
     model = List
     fields = "__all__"
     widgets = {'imgs': forms.CheckboxSelectMultiple()}
Ejemplo n.º 13
0
class BiletForm(forms.Form):
    MONTHS = {
        1: ('styczeń'),
        2: ('luty'),
        3: ('marzec'),
        4: ('kwiecień'),
        5: ('maj'),
        6: ('czerwiec'),
        7: ('lipiec'),
        8: ('sierpień'),
        9: ('wrzesień'),
        10: ('październik'),
        11: ('listopad'),
        12: ('grudzień')
    }
    PLUTONY = ((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))
    MIESIACE = (('styczeń', 'styczeń'), ('luty', 'luty'), ('marzec', 'marzec'),
                ('kwiecień', 'kwiecień'), ('maj', 'maj'),
                ('czerwiec', 'czerwiec'), ('lipiec', 'lipiec'), ('sierpień',
                                                                 'sierpień'),
                ('wrzesień', 'wrzesień'), ('październik', 'październik'),
                ('listopad', 'listopad'), ('grudzień', 'grudzień'))
    STOPNIE = (('szer. pchor.', 'szer. pchor.'), ('st. szer. pchor.',
                                                  'st. szer. pchor.'),
               ('kpr. pchor.', 'kpr. pchor.'), ('st. kpr. pchor.',
                                                'st. kpr. pchor.'),
               ('plut. pchor.', 'plut. pchor.'), ('sierż. pchor.',
                                                  'sierż. pchor.'))
    TYP = (('przepustkę jednorazową', 'PJ'), ('urlop', 'Urlop'))
    TAM = (('', 'w jedną stronę'), (' i z powrotem', 'w dwie strony'))
    POCIAGI = ("osobowym", "Osobowy"), ("pospiesznym", "TLK"), ("ekspresowym",
                                                                "IC/EIC/EIP")
    AUTOBUSY = ("zwykłej", "Zwykły"), ("przyspieszonej", "Przyspieszony")

    def clean(self):
        cleaned_data = self.cleaned_data
        end_date = cleaned_data.get('data_powrotu')
        start_date = cleaned_data.get('data_wyjazdu')
        typ_pociagu = cleaned_data.get('typ_pociagu')
        typ_autobusu = cleaned_data.get('typ_autobusu')
        typ = cleaned_data.get('typ')
        print(typ)
        PJ72 = cleaned_data.get('PJ72')
        roznica_dni = end_date - start_date
        if end_date and start_date:
            if end_date < start_date:
                self.add_error(
                    'data_powrotu',
                    'Data powrotu nie może być przed datą wyjazdu.')
        if len(typ_pociagu) == 0 and len(typ_autobusu) == 0:
            self.add_error('typ_autobusu', 'Wybierz środek transportu.')

        if roznica_dni.days >= 2 and not PJ72 and typ == 'przepustkę jednorazową':
            self.add_error('PJ72', 'Upewnij się, czy to była PJ 72?')
        return cleaned_data

    typ = forms.CharField(
        widget=forms.Select(choices=TYP, attrs={'class': 'normal'}))
    PJ72 = forms.BooleanField(help_text="Zaznacz jeśli to była PJ 72h",
                              required=False,
                              label='PJ 72h')
    data_wyjazdu = forms.DateField(
        widget=DateInput,
        initial=date.today(),
        label="Data rozpoczęcia PJ/urlopu",
        help_text=
        "Data rozpoczęcia urlopu/PJ z ROZKAZU, nie fizycznego wyjazdu (zazwyczaj wyjeżdża się dzień wcześniej)"
    )
    data_powrotu = forms.DateField(widget=DateInput,
                                   initial=date.today(),
                                   label="Data końca PJ/urlopu")
    tam_z_powrotem = forms.CharField(
        widget=forms.Select(choices=TAM, attrs={'class': 'normal'}),
        required=False,
        label="W jedną / w dwie strony",
    )
    miasto = forms.CharField(max_length=30,
                             label="Miasto podróży (z biletu):",
                             widget=forms.TextInput(attrs={'class': 'normal'}),
                             help_text="NIE WPISYWAĆ WARSZAWA")
    miesiac = forms.CharField(
        widget=forms.Select(choices=MIESIACE, attrs={'class': 'normal'}),
        label="Miesiąc",
        help_text="Miesiąc za jaki chcesz otrzymać należność")
    typ_pociagu = forms.MultipleChoiceField(
        choices=POCIAGI,
        widget=forms.CheckboxSelectMultiple(attrs={'class': 'xxx'}),
        required=False,
        label="Typ pociągu")
    typ_autobusu = forms.MultipleChoiceField(
        choices=AUTOBUSY,
        widget=forms.CheckboxSelectMultiple(attrs={'class': 'czekbox'}),
        required=False)
    kwota = forms.DecimalField(
        decimal_places=2,
        max_digits=10,
        label="Suma kwot z biletów",
        required=True,
        widget=forms.NumberInput(attrs={'class': 'normal'}))
    zgoda = forms.BooleanField(
        help_text=
        "Zgadzam się na przetwarzanie danych potrzebnych do sporządzenia rozkazu zgodnie z informacjami zawartymi w zakładce 'FAQ' w punkcie 10."
    )
Ejemplo n.º 14
0
def new_studentform(request):
    user_form=GenericCreationForm()
    profileinlineformset= inlineformset_factory(User,studentprofile,fields=('image','mobile_number','parents_number','department','semester','dob','address','roll_no','batch','Class','subject'),widgets={'subject':f.CheckboxSelectMultiple(attrs={'class':'checkbox'})})             
    formset=profileinlineformset()
    
    if request.method=='POST':
        user_form=GenericCreationForm(request.POST)
        formset=profileinlineformset(request.POST)
        
        if user_form.is_valid():
            created_user=user_form.save(commit=False)
            created_user.is_student=True
            created_user.is_active=False
            formset = profileinlineformset(request.POST,request.FILES,instance=created_user)
            
            if formset.is_valid():
            
                created_user.save()
                formset.save()
            
                errors=[err(e="Please Reach to Admin and Register Your ID.",link=" "),err(e="Your Account is InActive It will be activated by admin.",link=" ")]
                return render(request,'error.html',{'errors':errors})

    return render(request,'student/signup.html',{"user_form":user_form,"formset":formset,})
Ejemplo n.º 15
0
class CaseModelForm(forms.ModelForm):
    default_tester = UserField(required=False)

    is_automated = forms.MultipleChoiceField(
        choices=AUTOMATED_CHOICES,
        widget=forms.CheckboxSelectMultiple(),
    )
    is_automated_proposed = forms.BooleanField(label='Autoproposed',
                                               widget=forms.CheckboxInput(),
                                               required=False)

    product = forms.ModelChoiceField(
        label="Product",
        queryset=Product.objects.all(),
        empty_label=None,
    )
    category = forms.ModelChoiceField(
        label="Category",
        queryset=TestCaseCategory.objects.none(),
        empty_label=None,
    )
    component = forms.ModelMultipleChoiceField(
        label="Components",
        queryset=Component.objects.none(),
        required=False,
    )

    case_status = forms.ModelChoiceField(
        label="Case status",
        queryset=TestCaseStatus.objects.all(),
        empty_label=None,
    )

    priority = forms.ModelChoiceField(
        label="Priority",
        queryset=Priority.objects.all(),
        empty_label=None,
    )

    class Meta:
        model = TestCase
        exclude = ('author', )
        widgets = {
            'default_tester': UserField(),
        }

    # def clean_alias(self):
    #    data = self.cleaned_data['alias']
    #    tc_count = TestCase.objects.filter(alias = data).count()
    #
    #    if tc_count == 0:
    #        return data
    #    raise forms.ValidationError('Duplicated alias exist in database.')

    def clean_is_automated(self):
        data = self.cleaned_data['is_automated']
        if len(data) == 2:
            return 2

        if len(data):
            return data[0]

        return data

    def populate(self, product_id=None):
        if product_id:
            self.fields['category'].queryset = TestCaseCategory.objects.filter(
                product__id=product_id)
            self.fields['component'].queryset = Component.objects.filter(
                product__id=product_id)
        else:
            self.fields['category'].queryset = TestCaseCategory.objects.all()
            self.fields['component'].queryset = Component.objects.all()
Ejemplo n.º 16
0
class SignupFormExtra(SignupForm):
    """
    A form to add extra fields to the signup form.
    """
    first_name = forms.CharField(label=_('First name'),
                                 max_length=30,
                                 required=True)
    last_name = forms.CharField(label=_('Last name'),
                                max_length=30,
                                required=True)
    country = forms.ChoiceField(COUNTRIES, required=True)

    organization = forms.CharField(label=_('Organization'),
                                   max_length=255,
                                   required=True)

    profiles = forms.ModelMultipleChoiceField(label=_('I am a (select all that apply):'),
                                                required=True,
                                                queryset=Profile.objects.all(),
                                                widget=forms.CheckboxSelectMultiple())


    interests = forms.ModelMultipleChoiceField(label=_('I am interested in (select all that apply):'),
                                                required=True,
                                                queryset=Questionnaire.objects.filter(disable='False'),
                                                widget=forms.CheckboxSelectMultiple())

    paginator = forms.ChoiceField(label=_('Select default value for paginations:'),
                                        choices = options
                                    )

    mail_news = forms.BooleanField(label=_('Receive weekly newsletter e-mail with database updates ?'),
                                    required=False, initial=True
                                    )

    mail_not = forms.BooleanField(label=_('Receive all notifications also over e-mail ?'),
                                    required=False, initial=False
                                    )

    def __init__(self, *args, **kw):
        """
        A bit of hackery to get the added fields at the top of the
        form instead at the end.

        """
        super(SignupFormExtra, self).__init__(*args, **kw)
        # Delete the username field
        del self.fields['username']

        # Put the new fields at the top

        if Profile.objects.all().count() and Questionnaire.objects.all().count():
            self.fields.keyOrder = ['first_name', 'last_name', 'country', 'organization', 'email', 'password1', 'password2', 'profiles', 'interests', 'paginator','mail_news', 'mail_not']
        elif Profile.objects.all().count():
            self.fields.keyOrder = ['first_name', 'last_name', 'country', 'organization', 'email', 'password1', 'password2', 'profiles', 'paginator', 'mail_news', 'mail_not']
        elif Questionnaire.objects.all().count():
            self.fields.keyOrder = ['first_name', 'last_name', 'country', 'organization', 'email', 'password1', 'password2', 'interests','paginator', 'mail_news', 'mail_not']
        else:
            self.fields.keyOrder = ['first_name', 'last_name', 'country', 'organization', 'email', 'password1', 'password2', 'paginator','mail_news', 'mail_not']

    def save(self):
        """
        Override the save method to save additional fields to the user profile
        and override username with email.

        """
        # Use trimmed email as username
        username = self.cleaned_data['email'][:30]
        try:
            get_user_model().objects.get(username__iexact=username)
        except get_user_model().DoesNotExist:
            pass
        else:  # Fallback to randomly assigned username
            while True:
                username = sha_constructor(str(random.random())).hexdigest()[:5]
                try:
                    get_user_model().objects.get(username__iexact=username)
                except get_user_model().DoesNotExist:
                    break

        self.cleaned_data['username'] = username


        # First save the parent form and get the user.
        new_user = super(SignupFormExtra, self).save()

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.save()
        user_profile = new_user.get_profile()
        user_profile.country = self.cleaned_data['country']
        user_profile.organization = self.cleaned_data['organization']
        try:
            user_profile.paginator = int(self.cleaned_data['paginator'])
        except KeyError:
            user_profile.paginator = 5

        try:
            user_profile.mail_news = self.cleaned_data['mail_news']
        except KeyError:
            user_profile.mail_news = True

        try:
            user_profile.mail_not = self.cleaned_data['mail_not']
        except KeyError:
            user_profile.mail_not = False

        # Add selected profiles
        if (Profile.objects.all().count()):
            selected_profiles = self.cleaned_data['profiles']
            for sp in selected_profiles:
                prof = Profile.objects.get(name=sp)
                user_profile.profiles.add(prof)

        # Add selected interests
        if (Questionnaire.objects.all().count()):
            selected_interests = self.cleaned_data['interests']
            for inter in selected_interests:
                i = Questionnaire.objects.get(name=inter)
                user_profile.interests.add(i)

        user_profile.save()

        # Userena expects to get the new user from this form, so return the new
        # user.
        return new_user
Ejemplo n.º 17
0
class DNSSECOptionsForm(forms.Form):
    RR_CHOICES = (('all', '--All--'),
            (dns.rdatatype.A, dns.rdatatype.to_text(dns.rdatatype.A)),
            (dns.rdatatype.AAAA, dns.rdatatype.to_text(dns.rdatatype.AAAA)),
            (dns.rdatatype.TXT, dns.rdatatype.to_text(dns.rdatatype.TXT)),
            (dns.rdatatype.PTR, dns.rdatatype.to_text(dns.rdatatype.PTR)),
            (dns.rdatatype.MX, dns.rdatatype.to_text(dns.rdatatype.MX)),
            (dns.rdatatype.NS, dns.rdatatype.to_text(dns.rdatatype.NS)),
            (dns.rdatatype.SOA, dns.rdatatype.to_text(dns.rdatatype.SOA)),
            (dns.rdatatype.CNAME, dns.rdatatype.to_text(dns.rdatatype.CNAME)),
            (dns.rdatatype.SRV, dns.rdatatype.to_text(dns.rdatatype.SRV)),
            (dns.rdatatype.NAPTR, dns.rdatatype.to_text(dns.rdatatype.NAPTR)),
            (dns.rdatatype.TLSA, dns.rdatatype.to_text(dns.rdatatype.TLSA)))

    A_CHOICES = (('all', '--All--'),
            (1, '1 - RSA/MD5'),
            (3, '3 - DSA/SHA1'),
            (5, '5 - RSA/SHA-1'),
            (6, '6 - DSA-NSEC3-SHA1'),
            (7, '7 - RSASHA1-NSEC3-SHA1'),
            (8, '8 - RSA/SHA-256'),
            (10, '10 - RSA/SHA-512'),
            (12, '12 - GOST R 34.10-2001'),
            (13, '13 - ECDSA Curve P-256 with SHA-256'),
            (14, '14 - ECDSA Curve P-384 with SHA-384'),)

    DS_CHOICES = (('all', '--All--'),
            (1, '1 - SHA-1'),
            (2, '2 - SHA-256'),
            (3, '3 - GOST R 34.11-94'),
            (4, '4 - SHA-384'),)

    ANCHOR_CHOICES = (('.', 'Root zone KSK'),)

    rr = forms.MultipleChoiceField(label='RR types:', choices=RR_CHOICES, initial=['all'], required=True,
            help_text='Select the RR types to be considered in the analysis (note that not all RR types are available for all names).')
    a = forms.MultipleChoiceField(label='DNSSEC algorithms:', choices=A_CHOICES, initial=['all'], required=False,
            help_text='Select the DNSSEC algorithms that should be considered in the analysis.  Selecting no algorithms is equivalent to evaluating a zone as if unsigned.')
    ds = forms.MultipleChoiceField(label='DS digest algorithms:', choices=DS_CHOICES, initial=['all'], required=False,
            help_text='Select the DS digest algorithms that should be considered in the analysis.')
    doe = forms.BooleanField(label='Denial of existence:', initial=False, required=False, widget=forms.CheckboxInput(attrs={'class': 'no-border'}),
            help_text='Show authenticated denial of existence for non-existent RRsets.')
    red = forms.BooleanField(label='Redundant edges:', initial=False, required=False, widget=forms.CheckboxInput(attrs={'class': 'no-border'}),
            help_text='Show redundant edges between DNSKEYs.  Normally redundant edges are pruned to simplify the graph.')
    ta = LenientMultipleChoiceField(label='Trust anchors:', choices=ANCHOR_CHOICES, initial=['.'], required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'no-border'}),
            help_text='Use KSKs from the following zones as trust anchors for the DNSSEC analysis: the root zone; and/or the KSK for ISC\'s DNSSEC-lookaside validation (DLV) service.')
    tk = forms.CharField(label='Additional trusted keys:', initial='', required=False, widget=forms.Textarea(attrs={'cols': 50, 'rows': 5}),
            help_text='Use the following DNSKEY(s) as additional trust anchors for the DNSSEC analysis.  DNSKEYs should be entered one per line, in zone file format.')

    def clean_rr(self):
        if 'all' in self.cleaned_data['rr']:
            return map(int, [rr[0] for rr in self.RR_CHOICES if rr[0] != 'all'])
        else:
            return map(int, self.cleaned_data['rr'])

    def clean_a(self):
        if 'all' in self.cleaned_data['a']:
            return map(int, [a[0] for a in self.A_CHOICES if a[0] != 'all'])
        else:
            return map(int, self.cleaned_data['a'])

    def clean_ds(self):
        if 'all' in self.cleaned_data['ds']:
            return map(int, [ds[0] for ds in self.DS_CHOICES if ds[0] != 'all'])
        else:
            return map(int, self.cleaned_data['ds'])

    def clean_ta(self):
        ta_all = get_trusted_keys(_implicit_tk_str)
        names = set()
        for name in self.cleaned_data['ta']:
            try:
                names.add(dns.name.from_text(name))
            except dns.exception.DNSException:
                raise forms.ValidationError('Invalid domain name entered: %s!' % name)
        ta = []
        for name, key in ta_all:
            if name in names:
                ta.append((name,key))
        return ta

    def clean_tk(self):
        try:
            return get_trusted_keys(self.cleaned_data['tk'])
        except:
            raise forms.ValidationError('Unable to process trusted keys!')
Ejemplo n.º 18
0
class OrderForm(forms.Form):
    meniu = forms.ModelMultipleChoiceField(
        queryset=Meniu.objects.all(),
        widget=forms.CheckboxSelectMultiple(),
        required=False)
Ejemplo n.º 19
0
class AppointmentForm(forms.Form):
    appoint = AdvancedModelMultipleChoiceField(
        Application.objects.none(),
        widget=forms.CheckboxSelectMultiple(),
        required=False,
    )
    overturn = forms.CharField(
        required=False,
        label=_('Person number'),
        help_text=_('Enter a comma separated list of person numbers you want '
                    'to appoint to the position, even though did not apply for'
                    ' the position.'))

    def __init__(self, position, *args, **kwargs):
        super(AppointmentForm, self).__init__(*args, **kwargs)
        self.position = position
        self.fields['appoint'].queryset = position.applications.filter(
            status__in=['submitted', 'approved', 'appointed', 'turned_down'])
        self.initial['appoint'] = position.applications.filter(
            status='appointed')

    def clean_overturn(self):
        string = self.cleaned_data['overturn']
        string = string.replace(' ', '')
        if string == '':
            return []
        else:
            pnrs = string.split(',')
            users = []
            for pnr in pnrs:
                melos_id = MelosClient.get_melos_id(pnr)

                if not get_user_model().objects.filter(
                        melos_id=melos_id).exists() or melos_id is False:
                    raise forms.ValidationError(
                        _('No user with the person number %(pnr)s exists.'),
                        params={'pnr': pnr},
                    )
                elif self.position.applications.filter(
                        applicant__melos_id=melos_id, ).exclude(
                            status='draft').exists():
                    raise forms.ValidationError(
                        _('User with person number %(pnr)s already applied for'
                          ' this position and can not be appointed through the'
                          ' overturn field.'),
                        params={'pnr': pnr},
                    )
                else:
                    users.append(get_user_model().objects.filter(
                        melos_id=melos_id).first())
            return users

    def clean(self):
        super(AppointmentForm, self).clean()
        appoint = self.cleaned_data.get('appoint', [])
        overturn = self.cleaned_data.get('overturn', [])
        nr_appointment = len(appoint) + len(overturn)
        if nr_appointment > self.position.appointments:
            raise forms.ValidationError(
                _('You cannot appoint %(current)s applicants. The maximum '
                  'for this position is %(max)s.'),
                params={
                    'current': nr_appointment,
                    'max': self.position.appointments,
                },
            )
        return self.cleaned_data

    def save(self):
        for application in self.fields['appoint'].queryset:
            if application in self.cleaned_data['appoint']:
                application.status = 'appointed'

            else:
                application.status = 'turned_down'
            application.save()

        for user in self.cleaned_data['overturn']:
            appl, created = Application.objects.get_or_create(
                position=self.position,
                applicant=user,
                defaults={'status': 'appointed'})
            if not created:
                appl.status = 'appointed'
                appl.save()
Ejemplo n.º 20
0
class GroupForm2(forms.Form):
    Reporter_choices = [[x.id, x.user_name] for x in Reporter.objects.all()]
    Select_Users = forms.MultipleChoiceField(
        choices=Reporter_choices,
        widget=forms.CheckboxSelectMultiple(),
        required=False)
Ejemplo n.º 21
0
class MailForm(forms.Form):
    recipients = forms.ChoiceField(
        label=_('Send email to'),
        widget=forms.RadioSelect,
        initial='orders',
        choices=[]
    )
    sendto = forms.MultipleChoiceField()  # overridden later
    subject = forms.CharField(label=_("Subject"))
    message = forms.CharField(label=_("Message"))
    items = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple(
            attrs={'class': 'scrolling-multiple-choice'}
        ),
        label=_('Only send to people who bought'),
        required=True,
        queryset=Item.objects.none()
    )
    filter_checkins = forms.BooleanField(
        label=_('Filter check-in status'),
        required=False
    )
    checkin_lists = SafeModelMultipleChoiceField(queryset=CheckinList.objects.none(), required=False)  # overridden later
    not_checked_in = forms.BooleanField(label=_("Send to customers not checked in"), required=False)
    subevent = forms.ModelChoiceField(
        SubEvent.objects.none(),
        label=_('Only send to customers of'),
        required=False,
        empty_label=pgettext_lazy('subevent', 'All dates')
    )

    def _set_field_placeholders(self, fn, base_parameters):
        phs = [
            '{%s}' % p
            for p in sorted(get_available_placeholders(self.event, base_parameters).keys())
        ]
        ht = _('Available placeholders: {list}').format(
            list=', '.join(phs)
        )
        if self.fields[fn].help_text:
            self.fields[fn].help_text += ' ' + str(ht)
        else:
            self.fields[fn].help_text = ht
        self.fields[fn].validators.append(
            PlaceholderValidator(phs)
        )

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

        recp_choices = [
            ('orders', _('Everyone who created a ticket order'))
        ]
        if event.settings.attendee_emails_asked:
            recp_choices += [
                ('attendees', _('Every attendee (falling back to the order contact when no attendee email address is '
                                'given)')),
                ('both', _('Both (all order contact addresses and all attendee email addresses)'))
            ]
        self.fields['recipients'].choices = recp_choices

        self.fields['subject'] = I18nFormField(
            label=_('Subject'),
            widget=I18nTextInput, required=True,
            locales=event.settings.get('locales'),
        )
        self.fields['message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea, required=True,
            locales=event.settings.get('locales'),
        )
        self._set_field_placeholders('subject', ['event', 'order', 'position_or_address'])
        self._set_field_placeholders('message', ['event', 'order', 'position_or_address'])
        choices = list(Order.STATUS_CHOICE)
        if not event.settings.get('payment_term_expire_automatically', as_type=bool):
            choices.append(
                ('overdue', _('pending with payment overdue'))
            )
        self.fields['sendto'] = forms.MultipleChoiceField(
            label=_("Send to customers with order status"),
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'scrolling-multiple-choice'}
            ),
            choices=choices
        )
        if not self.initial.get('sendto'):
            self.initial['sendto'] = ['p', 'n']

        self.fields['items'].queryset = event.items.all()
        if not self.initial.get('items'):
            self.initial['items'] = event.items.all()

        self.fields['checkin_lists'].queryset = event.checkin_lists.all()
        self.fields['checkin_lists'].widget = Select2Multiple(
            attrs={
                'data-model-select2': 'generic',
                'data-select2-url': reverse('control:event.orders.checkinlists.select2', kwargs={
                    'event': event.slug,
                    'organizer': event.organizer.slug,
                }),
                'data-placeholder': _('Send to customers checked in on list'),
            }
        )
        self.fields['checkin_lists'].widget.choices = self.fields['checkin_lists'].choices
        self.fields['checkin_lists'].label = _('Send to customers checked in on list')

        if event.has_subevents:
            self.fields['subevent'].queryset = event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2': 'event',
                    'data-select2-url': reverse('control:event.subevents.select2', kwargs={
                        'event': event.slug,
                        'organizer': event.organizer.slug,
                    }),
                    'data-placeholder': pgettext_lazy('subevent', 'Date')
                }
            )
            self.fields['subevent'].widget.choices = self.fields['subevent'].choices
        else:
            del self.fields['subevent']
Ejemplo n.º 22
0
 def __init__(self, *args, **kwargs):
     instrument = kwargs.pop('instrument')
     super(InstrumentAnomalySubmitForm, self).__init__(*args, **kwargs)
     self.fields['anomaly_choices'] = forms.MultipleChoiceField(choices=ANOMALY_CHOICES_PER_INSTRUMENT[instrument], widget=forms.CheckboxSelectMultiple())
     self.instrument = instrument
Ejemplo n.º 23
0
class PrototypeMetadataForm(forms.Form):
    default_input_size = '60'

    element = meta_lookup('subject')
    subject = forms.MultipleChoiceField(
        choices=SUBJECT_AREAS,
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        widget=forms.CheckboxSelectMultiple(attrs={'data_value': element.id}),
        required=True)

    element = meta_lookup('language')
    language = forms.MultipleChoiceField(
        choices=LANGUAGES_NISO,
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        widget=forms.CheckboxSelectMultiple(attrs={'data_value': element.id}),
        required=False)

    element = meta_lookup('ic_heritage_learners')
    ic_heritage_learners = forms.ChoiceField(
        choices=INSTRUCTIONAL_CONTEXTS['heritage-learners'],
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.RadioSelect(attrs={'class': ''}),
        required=False)

    element = meta_lookup('ic_target_audience_description')
    ic_target_audience_description = forms.CharField(
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.Textarea(attrs={'class': 'form-control'}),
        required=False)

    element = meta_lookup('ic_target_audience_role')
    ic_target_audience_role = forms.CharField(
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=False)

    element = meta_lookup('ic_target_audience_location')
    ic_target_audience_location = forms.CharField(
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=False)

    element = meta_lookup('ic_product_description')
    ic_product_description = forms.CharField(
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.Textarea(attrs={'class': 'form-control'}),
        required=False)

    element = meta_lookup('ic_product_target_culture')
    ic_product_target_culture = forms.CharField(
        label=element.category_display,
        label_suffix=element.id_display,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        required=False)

    element = meta_lookup('lp_actfl_scale')
    lp_actfl_scale = forms.MultipleChoiceField(
        choices=LANGUAGE_PROFICIENCY['actfl'],
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        required=False)

    element = meta_lookup('lp_ilr_scale_listening')
    lp_ilr_scale_listening = forms.MultipleChoiceField(
        choices=LANGUAGE_PROFICIENCY['ilr-listening'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('lp_ilr_scale_reading')
    lp_ilr_scale_reading = forms.MultipleChoiceField(
        choices=LANGUAGE_PROFICIENCY['ilr-reading'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('lp_ilr_scale_speaking')
    lp_ilr_scale_speaking = forms.MultipleChoiceField(
        choices=LANGUAGE_PROFICIENCY['ilr-speaking'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('lp_ilr_scale_writing')
    lp_ilr_scale_writing = forms.MultipleChoiceField(
        choices=LANGUAGE_PROFICIENCY['ilr-writing'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('wr_goal_area_communication')
    wr_goal_area_communication = forms.MultipleChoiceField(
        choices=WR_GOAL_AREA['communication'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('wr_goal_area_cultures')
    wr_goal_area_cultures = forms.MultipleChoiceField(
        choices=WR_GOAL_AREA['cultures'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('wr_goal_area_connections')
    wr_goal_area_connections = forms.MultipleChoiceField(
        choices=WR_GOAL_AREA['connections'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('wr_goal_area_comparisons')
    wr_goal_area_comparisons = forms.MultipleChoiceField(
        choices=WR_GOAL_AREA['comparisons'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('wr_goal_area_communities')
    wr_goal_area_communities = forms.MultipleChoiceField(
        choices=WR_GOAL_AREA['communities'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('cs_interdisciplinary_themes')
    cs_interdisciplinary_themes = forms.MultipleChoiceField(
        choices=CENTURY_SKILLS['interdisciplinary-themes'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('cs_info_media_technology_skills')
    cs_info_media_technology_skills = forms.MultipleChoiceField(
        choices=CENTURY_SKILLS['information-media-technology-skills'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    element = meta_lookup('cs_like_career_skills')
    cs_like_career_skills = forms.MultipleChoiceField(
        choices=CENTURY_SKILLS['like-career-skills'],
        widget=forms.CheckboxSelectMultiple(attrs={'class': '', 'data_value': element.id}),
        label=element.category_display,
        label_suffix=element.id_display,
        help_text='Check all that apply.',
        required=False)

    def multiple_choice_fields(self):
        return [field_name for field_name, field_type in self.fields.items() if type(field_type) == forms.MultipleChoiceField]

    
    def display_order_fields(self):
        """ Returns the definition order of the field names. """
        return self.fields.keys()
Ejemplo n.º 24
0
Archivo: forms.py Proyecto: sgauri/hmw
class PalazzoForm(ModelForm):
    color = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(),
                                      choices=models.COLOR_CHOICES)
Ejemplo n.º 25
0
 def __init__(self, queryset, max_choice, **kwargs):
     self.max_choice = max_choice
     widget = forms.CheckboxSelectMultiple()
     super(LimitedCheckboxField, self).__init__(queryset, **kwargs)
Ejemplo n.º 26
0
                                            'use comma to split more than one '
                                            'case id. e.g. "111, 222"')
        else:
            raise forms.ValidationError('Please input valid case id(s). '
                                        'use comma to split more than one '
                                        'case id. e.g. "111, 222"')


# =========== Mist Forms ==============


class CloneCaseForm(forms.Form):
    case = forms.ModelMultipleChoiceField(
        label='Test Case',
        queryset=TestCase.objects.all(),
        widget=forms.CheckboxSelectMultiple())
    plan = forms.ModelMultipleChoiceField(
        label='Test Plan',
        queryset=TestPlan.objects.all(),
        widget=forms.CheckboxSelectMultiple())
    copy_case = forms.BooleanField(
        label='Create a copy',
        help_text='Create a Copy (Unchecking will create a link to selected '
        'case)',
        required=False)
    maintain_case_orignal_author = forms.BooleanField(
        label='Keep original author',
        help_text='Keep original author (Unchecking will make me as author '
        'of the copied test case)',
        required=False)
    maintain_case_orignal_default_tester = forms.BooleanField(
Ejemplo n.º 27
0
 class Meta:
     model = History
     fields = '__all__'
     widgets = {
         'workshops': forms.CheckboxSelectMultiple(),
     }
Ejemplo n.º 28
0
class BaseCaseForm(forms.Form):
    summary = forms.CharField(label="Summary", )
    default_tester = UserField(label="Default tester", required=False)
    requirement = forms.CharField(label="Requirement", required=False)
    is_automated = forms.MultipleChoiceField(
        choices=AUTOMATED_CHOICES,
        widget=forms.CheckboxSelectMultiple(),
    )
    is_automated_proposed = forms.BooleanField(label='Autoproposed',
                                               required=False)
    script = forms.CharField(label="Script", required=False)
    arguments = forms.CharField(label="Arguments", required=False)
    alias = forms.CharField(label="Alias", required=False)
    extra_link = StripURLField(label='Extra link',
                               max_length=1024,
                               required=False)
    # sortkey = forms.IntegerField(label = 'Sortkey', required = False)
    case_status = forms.ModelChoiceField(label="Case status",
                                         queryset=TestCaseStatus.objects.all(),
                                         empty_label=None,
                                         required=False)
    priority = forms.ModelChoiceField(
        label="Priority",
        queryset=Priority.objects.all(),
        empty_label=None,
    )
    product = forms.ModelChoiceField(
        label="Product",
        queryset=Product.objects.all(),
        empty_label=None,
    )
    category = forms.ModelChoiceField(
        label="Category",
        queryset=TestCaseCategory.objects.none(),
        empty_label=None,
    )
    component = forms.ModelMultipleChoiceField(
        label="Components",
        queryset=Component.objects.none(),
        required=False,
    )
    notes = forms.CharField(label='Notes',
                            widget=forms.Textarea,
                            required=False)
    estimated_time = DurationField(label='Estimated Time',
                                   initial='0m',
                                   required=False)
    setup = forms.CharField(label="Setup", widget=TinyMCE, required=False)
    action = forms.CharField(label="Actions", widget=TinyMCE, required=False)
    effect = forms.CharField(label="Expect results",
                             widget=TinyMCE,
                             required=False)
    breakdown = forms.CharField(label="Breakdown",
                                widget=TinyMCE,
                                required=False)

    tag = forms.CharField(label="Tag", required=False)

    def __init__(self, *args, **kwargs):
        if args:
            self.notes_val = args[0].get('notes', None)
            self.script_val = args[0].get('script', None)
        elif kwargs:
            self.notes_val = kwargs.get('notes', None)
            self.script_val = kwargs.get('script', None)
        else:
            self.notes_val = ''
            self.script_val = ''
        super(BaseCaseForm, self).__init__(*args, **kwargs)

    def clean_is_automated(self):
        data = self.cleaned_data['is_automated']
        if len(data) == 2:
            return 2

        if len(data):
            # FIXME: Should data always be a list?
            try:
                return int(data[0])
            except ValueError:
                return data[0]

        return data

    def clean_script(self):
        if self.script_val == '':
            return u''
        elif self.script_val:
            return self.cleaned_data['script']
        else:
            return None

    def clean_notes(self):
        if self.notes_val == '':
            return u''
        elif self.notes_val:
            return self.cleaned_data['notes']
        else:
            return None

    # def clean_alias(self):
    #    data = self.cleaned_data['alias']
    #    tc_count = TestCase.objects.filter(alias = data).count()
    #
    #    if tc_count == 0:
    #        return data
    #
    #    raise forms.ValidationError('Duplicated alias exist in database.')

    def clean_tag(self):
        tags = []
        if self.cleaned_data['tag']:
            tag_names = TestTag.string_to_list(self.cleaned_data['tag'])
            tags = TestTag.get_or_create_many_by_name(tag_names)
        return tags

    def populate(self, product_id=None):
        if product_id:
            self.fields['category'].queryset = TestCaseCategory.objects.filter(
                product__id=product_id)
            self.fields['component'].queryset = Component.objects.filter(
                product__id=product_id)
        else:
            self.fields['category'].queryset = TestCaseCategory.objects.all()
            self.fields['component'].queryset = Component.objects.all()
Ejemplo n.º 29
0
    def settings_form_fields(self) -> dict:
        """
        When the event's administrator visits the event configuration
        page, this method is called to return the configuration fields available.

        It should therefore return a dictionary where the keys should be (unprefixed)
        settings keys and the values should be corresponding Django form fields.

        The default implementation returns the appropriate fields for the ``_enabled``,
        ``_fee_abs``, ``_fee_percent`` and ``_availability_date`` settings mentioned above.

        We suggest that you return an ``OrderedDict`` object instead of a dictionary
        and make use of the default implementation. Your implementation could look
        like this::

            @property
            def settings_form_fields(self):
                return OrderedDict(
                    list(super().settings_form_fields.items()) + [
                        ('bank_details',
                         forms.CharField(
                             widget=forms.Textarea,
                             label=_('Bank account details'),
                             required=False
                         ))
                    ]
                )

        .. WARNING:: It is highly discouraged to alter the ``_enabled`` field of the default
                     implementation.
        """
        places = settings.CURRENCY_PLACES.get(self.event.currency, 2)
        d = OrderedDict([
            ('_enabled',
             forms.BooleanField(
                 label=_('Enable payment method'),
                 required=False,
             )),
            ('_availability_date',
             RelativeDateField(
                 label=_('Available until'),
                 help_text=_('Users will not be able to choose this payment provider after the given date.'),
                 required=False,
             )),
            ('_invoice_text',
             I18nFormField(
                 label=_('Text on invoices'),
                 help_text=_('Will be printed just below the payment figures and above the closing text on invoices. '
                             'This will only be used if the invoice is generated before the order is paid. If the '
                             'invoice is generated later, it will show a text stating that it has already been paid.'),
                 required=False,
                 widget=I18nTextarea,
                 widget_kwargs={'attrs': {'rows': '2'}}
             )),
            ('_total_min',
             forms.DecimalField(
                 label=_('Minimum order total'),
                 help_text=_('This payment will be available only if the order total is equal to or exceeds the given '
                             'value. The order total for this purpose may be computed without taking the fees imposed '
                             'by this payment method into account.'),
                 localize=True,
                 required=False,
                 decimal_places=places,
                 widget=DecimalTextInput(places=places)
             )),
            ('_total_max',
             forms.DecimalField(
                 label=_('Maximum order total'),
                 help_text=_('This payment will be available only if the order total is equal to or below the given '
                             'value. The order total for this purpose may be computed without taking the fees imposed '
                             'by this payment method into account.'),
                 localize=True,
                 required=False,
                 decimal_places=places,
                 widget=DecimalTextInput(places=places)
             )),
            ('_fee_abs',
             forms.DecimalField(
                 label=_('Additional fee'),
                 help_text=_('Absolute value'),
                 localize=True,
                 required=False,
                 decimal_places=places,
                 widget=DecimalTextInput(places=places)
             )),
            ('_fee_percent',
             forms.DecimalField(
                 label=_('Additional fee'),
                 help_text=_('Percentage of the order total.'),
                 localize=True,
                 required=False,
             )),
            ('_fee_reverse_calc',
             forms.BooleanField(
                 label=_('Calculate the fee from the total value including the fee.'),
                 help_text=_('We recommend to enable this if you want your users to pay the payment fees of your '
                             'payment provider. <a href="{docs_url}" target="_blank" rel="noopener">Click here '
                             'for detailed information on what this does.</a> Don\'t forget to set the correct fees '
                             'above!').format(docs_url='https://docs.pretix.eu/en/latest/user/payments/fees.html'),
                 required=False
             )),
            ('_restricted_countries',
             forms.MultipleChoiceField(
                 label=_('Restrict to countries'),
                 choices=Countries(),
                 help_text=_('Only allow choosing this payment provider for invoice addresses in the selected '
                             'countries. If you don\'t select any country, all countries are allowed. This is only '
                             'enabled if the invoice address is required.'),
                 widget=forms.CheckboxSelectMultiple(
                     attrs={'class': 'scrolling-multiple-choice'}
                 ),
                 required=False,
                 disabled=not self.event.settings.invoice_address_required
             )),
        ])
        d['_restricted_countries']._as_type = list
        return d
Ejemplo n.º 30
0
 def __init__(self, user, friends=[], vals=[], *args, **kwargs):
     super(FriendsForm, self).__init__(*args, **kwargs)
     self.fields['friends'] = forms.MultipleChoiceField(
         choices=[(item.user, item.user) for item in friends],
         widget=forms.CheckboxSelectMultiple(),
         initial=vals)