コード例 #1
0
 def test_integerfield_float(self):
     f = IntegerField()
     self.assertEqual(1, f.clean(1.0))
     self.assertEqual(1, f.clean('1.0'))
     self.assertEqual(1, f.clean(' 1.0 '))
     self.assertEqual(1, f.clean('1.'))
     self.assertEqual(1, f.clean(' 1. '))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('1.5')
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('…')
コード例 #2
0
ファイル: views.py プロジェクト: nicolastrres/Nitrate
def remove(request, link_id):
    ''' Remove a specific link with ID ``link_id`` '''

    from django.forms import IntegerField
    from django.forms import ValidationError

    field = IntegerField(min_value=1)
    try:
        value = field.clean(link_id)
    except ValidationError, err:
        jd = json.dumps({'rc': 1, 'response': '\n'.join(err.messages)})
        return HttpJSONResponseBadRequest(content=jd)
コード例 #3
0
 def test_integerfield_3(self):
     f = IntegerField(max_value=10)
     self.assertWidgetRendersTo(f, '<input max="10" type="number" name="f" id="id_f" required>')
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean(None)
     self.assertEqual(1, f.clean(1))
     self.assertEqual(10, f.clean(10))
     with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
         f.clean(11)
     self.assertEqual(10, f.clean('10'))
     with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
         f.clean('11')
     self.assertEqual(f.max_value, 10)
     self.assertIsNone(f.min_value)
コード例 #4
0
ファイル: models.py プロジェクト: TibbersBear/openfisca
 def __init__(self, *args, **kwargs):
     widgetAttr = {'size':'8', 
                   'align': 'right',
                   'maxlength':'9', 
                   'style' : "text-align: right"
                   }
     wid = TextInput(attrs=widgetAttr)
     fieldAttr = {'max_value': 999999999, 
                  'min_value': 0,
                  'required' : False,
                  'localize': True
                  }
     fieldAttr.update(kwargs)
     IntegerField.__init__(self, widget = wid, **fieldAttr)
コード例 #5
0
ファイル: test_integerfield.py プロジェクト: 277800076/django
 def test_integerfield_5(self):
     f = IntegerField(min_value=10, max_value=20)
     self.assertWidgetRendersTo(f, '<input id="id_f" max="20" type="number" name="f" min="10" />')
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean(None)
     with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
         f.clean(1)
     self.assertEqual(10, f.clean(10))
     self.assertEqual(11, f.clean(11))
     self.assertEqual(10, f.clean('10'))
     self.assertEqual(11, f.clean('11'))
     self.assertEqual(20, f.clean(20))
     with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"):
         f.clean(21)
     self.assertEqual(f.max_value, 20)
     self.assertEqual(f.min_value, 10)
コード例 #6
0
ファイル: views.py プロジェクト: Nitrate/Nitrate
def remove(request, link_id):
    """Remove a specific link with ID ``link_id``"""

    from django.forms import IntegerField
    from django.forms import ValidationError

    field = IntegerField(min_value=1)
    try:
        value = field.clean(link_id)
    except ValidationError as err:
        return JsonResponseBadRequest({
            'rc': 1,
            'response': '\n'.join(err.messages)
        })

    try:
        LinkReference.unlink(value)
    except Exception as err:
        return JsonResponseBadRequest({'rc': 1, 'response': str(err)})

    return JsonResponse({
        'rc': 0,
        'response': 'Link has been removed successfully.'
    })
コード例 #7
0
class RecordForm(LRecordForm):

    sample_id = CharField(max_length=50, label='Sample ID:', widget=TextInput(attrs={'class': 'sample'}))
    seconds = IntegerField(initial=0, label='N seconds:', widget=NumberInput(attrs={'min':0, 'step':1, 'class': 'seconds'}))

    class Meta(LRecordForm.Meta):
        model = Record
        fields = ['date_from', 'time_from',
                  'date_to', 'time_to',
                  'user',
                  'wu',
                  'group', 'project', 'experiment', 'remark']

        labels = {'wu': 'WU:', 'date_from': 'From:', 'time_from':'Time:',
                  'date_to': 'To:', 'time_to': 'Time:',
                  'experiment': 'Experiment:',
                  }

        help_texts = {'date_from': 'The starting date of your run',
                      'date_to': 'The last date of your run',
                      'time_from': 'The first session of your run',
                      'time_to': 'The last session of your run',
                      'experiment': 'Pick an experiment'
                      }

        widgets = {
            'date_from' : DateInput(attrs={'type':'date', 'class':'datepicker dfrom time'}),
            'date_to' : DateInput(attrs={'type':'date', 'class':'datepicker dto time'}),
            'time_to' : Select(attrs={'class': 'tto time'}),
            'time_from': Select(attrs={'class': 'tfrom time'}),
            'remark' : Textarea(attrs={'placeholder': 'Enter some detail here about your experiment',
                                       'rows': '1', 'cols' :'50'}),
            'experiment': Select(attrs={'class': 'experiment', }),
            'group': Select(attrs={'class': 'group', }),
            'project': Select(attrs={'class': 'project', }),
            'user' : Select(attrs = {'placeholder': 'Surname Name', 'class': 'user'}),
            'wu' : NumberInput(attrs = {'required': False, 'class': 'uo', 'value': 0, 'min': 0, 'step':0.5,'style': 'width:10ch'}),
        }
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.help_text_inline = False
        self.helper.form_class = 'form-horizontal formclass'
        self.helper.form_id = 'form_id'
        self.helper.form_tag = True
        self.helper.layout = Layout(
                Div(
                    Row(
                        Column('date_from', css_class='form-group col-md-3'),
                        Column('time_from', css_class='form-group col-md-3'),
                        Column('wu', css_class='form-group col-md-4 uocol'),
                        Div(css_class='w-100'),
                        Column('date_to', css_class='form-group col-md-3'),
                        Column('time_to', css_class='form-group col-md-3'),
                        Column('experiment', css_class='form-group col-6'),
                        css_class='form-row'
                    ),
                    Row(Column('sample_id', css_class='form-group col-md-4 gi-col'),
                        Column('seconds', css_class='form-group col-md-4 gi-col'),
                        css_class='form-row gi-row',
                        ),
                    Row(Column('project', css_class='form-group col-md-8'),
                        css_class='form-row',
                    ),
                    Row(
                        Column('user', css_class='form-group col-md-4'),
                        Column('user_text_name', css_class='form-group col-md-3 usercol'),
                        Column('user_text_surname', css_class='form-group col-md-3 usercol'),
                        Column('group', css_class='form-group col-md-2'),
                        css_class='form-row'
                    ),
                    Row(
                        Column('remark', css_class='form-group mr-5'),
                        Column(FormActions(
                                        Button('okbutton', 'Submit', css_class='btn-primary okclass'), #form will be triggered using a popup jquery, see static/js/osp_records.js
                                        Reset('name', 'Reset', css_class='btn-secondary')
                                            ),css_class='form-group align-items-center')
                        ),
            )
        )

        super().__init__(*args, **kwargs)
        for field in self.fields:
            help_text = self.fields[field].help_text
            self.fields[field].help_text = None
            if help_text != '':
                if 'class' in self.fields[field].widget.attrs:
                    self.fields[field].widget.attrs['class'] += ' has-popover'
                self.fields[field].widget.attrs.update(
                    {'data - toggle': 'popover',
                     'data-content': help_text, 'data-placement': 'right',
                     'data-container': 'body'})
コード例 #8
0
class FilterForm(Form):
    review = IntegerField(required=False)
    level = IntegerField(required=False)
    hard = IntegerField(required=False)
コード例 #9
0
    def get_context(self, request, *args):
        """returns thread list data"""

        if len(args):
            user = args[0]
        else:
            user = request.user

        #get threads and the last visit time
        sender_id = IntegerField().clean(request.REQUEST.get(
            'sender_id', '-1'))

        if sender_id == -2:
            threads = Message.objects.get_threads(recipient=user, deleted=True)
        elif sender_id == -1:
            threads = Message.objects.get_threads(recipient=user)
        elif sender_id == user.id:
            threads = Message.objects.get_sent_threads(sender=user)
        else:
            sender = User.objects.get(id=sender_id)
            threads = Message.objects.get_threads(recipient=user,
                                                  sender=sender)

        threads = threads.order_by('-last_active_at')

        #for each thread we need to know if there is something
        #unread for the user - to mark "new" threads as bold
        threads_data = dict()
        for thread in threads:
            thread_data = dict()
            #determine status
            thread_data['status'] = 'new'
            #determine the senders info
            senders_names = thread.senders_info.split(',')
            if user.username in senders_names:
                senders_names.remove(user.username)
            thread_data['senders_info'] = ', '.join(senders_names)
            thread_data['thread'] = thread
            threads_data[thread.id] = thread_data

        ids = [thread.id for thread in threads]
        counts = Message.objects.filter(id__in=ids).annotate(
            responses_count=models.Count('descendants')).values(
                'id', 'responses_count')
        for count in counts:
            thread_id = count['id']
            responses_count = count['responses_count']
            threads_data[thread_id]['responses_count'] = responses_count

        last_visit_times = LastVisitTime.objects.filter(user=user,
                                                        message__in=threads)
        for last_visit in last_visit_times:
            thread_data = threads_data[last_visit.message_id]
            if thread_data['thread'].last_active_at <= last_visit.at:
                thread_data['status'] = 'seen'

        return {
            'threads': threads,
            'threads_count': threads.count(),
            'threads_data': threads_data,
            'sender_id': sender_id
        }
コード例 #10
0
class FilterTours(Form):
    min_price = IntegerField(required=False)
    max_price = IntegerField(required=False)
    data = DateField(required=False)
    country = CharField(required=False)
コード例 #11
0
ファイル: forms.py プロジェクト: aramrami/vulture-gui
class NetdataForm(ModelForm):
    history = IntegerField(
        label=_("History"),
        widget=Select(attrs={'class': 'form-control select2'},
                      choices=CHOICES_HISTORY),
        help_text=_(
            mark_safe(
                """This option controls the maximum size of the memory database in use by Netdata.<br/>
    <ul><li>3600 seconds (1 hour of chart data retention) uses 15 MB of RAM</li>
    <li>7200 seconds (2 hours of chart data retention) uses 30 MB of RAM</li>
    <li>14400 seconds (4 hours of chart data retention) uses 60 MB of RAM</li>
    <li>28800 seconds (8 hours of chart data retention) uses 120 MB of RAM</li>
    <li>43200 seconds (12 hours of chart data retention) uses 180 MB of RAM</li>
    <li>86400 seconds (24 hours of chart data retention) uses 360 MB of RAM</li></ul>"""
            )))

    class Meta:
        model = NetdataSettings
        fields = ('history', 'backend_enabled', 'backend_type',
                  'backend_host_tags', 'backend_destination',
                  'backend_data_source', 'backend_prefix',
                  'backend_update_every', 'backend_buffer_on_failure',
                  'backend_timeout', 'backend_send_hosts_matching',
                  'backend_send_charts_matching', 'backend_send_names_or_ids')

        widgets = {
            'backend_enabled':
            CheckboxInput(attrs={'class': "js-switch"}),
            'backend_type':
            Select(choices=BACKEND_TYPE_CHOICES,
                   attrs={'class': 'form-control select2'}),
            'backend_host_tags':
            TextInput(attrs={'class': 'form-control tags-input-comma'}),
            'backend_destination':
            TextInput(attrs={'class': 'form-control tags-input-space'}),
            'backend_data_source':
            Select(choices=DATA_SOURCE_CHOICES,
                   attrs={'class': 'form-control select2'}),
            'backend_prefix':
            TextInput(attrs={'class': 'form-control'}),
            'backend_update_every':
            NumberInput(attrs={'class': 'form-control'}),
            'backend_buffer_on_failure':
            NumberInput(attrs={'class': 'form-control'}),
            'backend_timeout':
            NumberInput(attrs={'class': 'form-control'}),
            'backend_send_hosts_matching':
            TextInput(attrs={'class': 'form-control tags-input-space'}),
            'backend_send_charts_matching':
            TextInput(attrs={'class': 'form-control tags-input-space'}),
            'backend_send_names_or_ids':
            CheckboxInput(attrs={'class': "js-switch"})
        }

    def __init__(self, *args, **kwargs):
        """ Initialize form and special attributes """
        super().__init__(*args, **kwargs)
        # All backend fields are not required in case of backend disabled
        for field_name in ('backend_type', 'backend_host_tags',
                           'backend_destination', 'backend_data_source',
                           'backend_prefix', 'backend_update_every',
                           'backend_buffer_on_failure', 'backend_timeout',
                           'backend_send_hosts_matching',
                           'backend_send_charts_matching',
                           'backend_send_names_or_ids'):
            self.fields[field_name].required = False
        self.initial['backend_host_tags'] = ','.join(
            self.initial.get('backend_host_tags', [])
            or self.fields['backend_host_tags'].initial)

    def clean_backend_host_tags(self):
        tags = self.cleaned_data.get('backend_host_tags')
        result = []
        if tags:
            for tag in tags:
                RegexValidator("^(\w+)=(\w+)$", tag)
                result.append(tag)
        return result

    def clean(self):
        cleaned_data = super().clean()
        # If backend is enabled, some fields are required
        if cleaned_data.get('backend_enabled'):
            for field_name in ('backend_type', 'backend_destination',
                               'backend_data_source', 'backend_prefix'):
                if not cleaned_data.get(field_name):
                    self.add_error(
                        field_name,
                        "This field is required if Backend is enabled.")
コード例 #12
0
class NotStaffUserForm(forms.Form):
    otp_pass = IntegerField(widget=TextInput(attrs={"class": "form-control"}))

    def __init__(self, *args, **kwargs):
        kwargs.pop('phone_number')
        super(NotStaffUserForm, self).__init__(*args, **kwargs)
コード例 #13
0
class CheckForm(Form):

    input_line = CharField(required=False)
    id = IntegerField(required=False)
コード例 #14
0
ファイル: formsets.py プロジェクト: yingcloud/django
 class CheckForm(Form):
     field = IntegerField(min_value=100)
コード例 #15
0
class AddCaseActionForm(ActionForm):
    number_cases = IntegerField(required=False)
    city = ModelChoiceField(queryset=City.objects.all(), required=False)
コード例 #16
0
 class DjangoForm(forms.Form):
     input = PathListField(
         required=True,
         initial=["$input"],
         help_text="Input paths (may be files or folders).")
     output = CharField(
         required=True,
         initial="$output",
         help_text="Output directory.  Must not already exist.")
     mapper_cmd = CharField(
         required=True,
         initial="<python yourscript.py --map>",
         help_text=
         "Command to execute for map tasks (exclusive with mapper_class).")
     mapper_class = CharField(
         required=False,
         initial="",
         help_text=
         "Class to execute for map tasks (exclusive with mapper_cmd).")
     combiner_class = CharField(
         required=False,
         help_text="(Optional) Class to execute as combiner.")
     reducer_cmd = CharField(
         required=False,
         initial="<python yourscript.py --reduce>",
         help_text=
         "(Optional.)  Command to execute for reduce tasks (exclusive with reducer_class)"
     )
     reducer_class = CharField(
         required=False,
         initial="",
         help_text=
         "Class to execute for reduce tasks (exclusive with reducer_cmd)")
     inputformat_class = ChoiceOrOtherField(
         required=False,
         initial="org.apache.hadoop.mapred.TextInputFormat",
         choices=(
             pair_up("org.apache.hadoop.mapred.TextInputFormat"),
             pair_up(
                 "org.apache.hadoop.mapred.SequenceFileAsTextInputFormat"),
         ),
         help_text="Built-in input format, or class of custom input format."
     )
     outputformat_class = ChoiceOrOtherField(
         required=False,
         initial="org.apache.hadoop.mapred.TextOutputFormat",
         choices=(pair_up("org.apache.hadoop.mapred.TextOutputFormat"), ),
         help_text="Built-in output format, or class of custom input format."
     )
     partitioner_class = CharField(
         required=False, help_text="(Optional) class name of partitioner.")
     num_reduce_tasks = IntegerField(
         required=False,
         initial=1,
         help_text="Number of reduce tasks.  Set to 0 to disable reducers.")
     inputreader = CharField(required=False,
                             help_text="(Optional) Inputreader spec.")
     cache_files = PathListField(
         required=False,
         initial=["<yourscript.py>"],
         label="Required Files",
         help_text="Files (on cluster) to send as part of job.")
     cache_archives = PathListField(
         required=False,
         help_text="Archives (zip, jar) (on cluster) to send as part of job."
     )
     hadoop_properties = KeyValueField(
         required=False,
         help_text='Hadoop options in format property=value.')
コード例 #17
0
 class BookingListAPIPostForm(Form):
     course = IntegerField()
     start_date = DateTimeField()
     end_date = DateTimeField()
     teacher = CharField(required=False)
     info = CharField(required=False)
コード例 #18
0
class BlockListGetForm(Form):
    """
    A form to validate query parameters in the block list retrieval endpoint
    """
    all_blocks = ExtendedNullBooleanField(required=False)
    block_counts = MultiValueField(required=False)
    depth = CharField(required=False)
    nav_depth = IntegerField(required=False, min_value=0)
    requested_fields = MultiValueField(required=False)
    return_type = ChoiceField(
        required=False,
        choices=[(choice, choice) for choice in ['dict', 'list']],
    )
    student_view_data = MultiValueField(required=False)
    usage_key = CharField(required=True)
    username = CharField(required=False)
    block_types_filter = MultiValueField(required=False)

    def clean_depth(self):
        """
        Get the appropriate depth.  No provided value will be treated as a
        depth of 0, while a value of "all" will be treated as unlimited depth.
        """
        value = self.cleaned_data['depth']
        if not value:
            return 0
        elif value == "all":
            return None
        try:
            return int(value)
        except ValueError:
            raise ValidationError(f"'{value}' is not a valid depth value.")  # lint-amnesty, pylint: disable=raise-missing-from

    def clean_requested_fields(self):
        """
        Return a set of `requested_fields`, merged with defaults of `type`
        and `display_name`
        """
        requested_fields = self.cleaned_data['requested_fields']

        # add default requested_fields
        return (requested_fields or set()) | {'type', 'display_name'}

    def clean_return_type(self):
        """
        Return valid 'return_type' or default value of 'dict'
        """
        return self.cleaned_data['return_type'] or 'dict'

    def clean_usage_key(self):
        """
        Ensure a valid `usage_key` was provided.
        """
        usage_key = self.cleaned_data['usage_key']

        try:
            usage_key = UsageKey.from_string(usage_key)
        except InvalidKeyError:
            raise ValidationError(
                f"'{str(usage_key)}' is not a valid usage key.")  # lint-amnesty, pylint: disable=raise-missing-from

        return usage_key.replace(
            course_key=modulestore().fill_in_run(usage_key.course_key))

    def clean(self):
        """
        Return cleaned data, including additional requested fields.
        """
        cleaned_data = super().clean()

        # Add additional requested_fields that are specified as separate
        # parameters, if they were requested.
        additional_requested_fields = [
            'student_view_data',
            'block_counts',
            'nav_depth',
            'block_types_filter',
        ]
        for additional_field in additional_requested_fields:
            field_value = cleaned_data.get(additional_field)
            if field_value or field_value == 0:  # allow 0 as a requested value
                cleaned_data['requested_fields'].add(additional_field)

        usage_key = cleaned_data.get('usage_key')
        if not usage_key:
            return

        cleaned_data['user'] = self._clean_requested_user(
            cleaned_data, usage_key.course_key)
        return cleaned_data

    def clean_username(self):
        """
        Return cleaned username.

        Overrides the default behaviour that maps an empty string to None. This
        allows us to differentiate between no username being provided (None) vs
        an empty username being provided ('').
        """
        # In case all_blocks is specified, ignore the username.
        if self.cleaned_data.get('all_blocks', False):
            return None

        # See if 'username' was provided as a parameter in the raw data.
        # If so, we return the already-cleaned version of that, otherwise we
        # return None
        if 'username' in self.data:
            return self.cleaned_data['username']
        return None

    def _clean_requested_user(self, cleaned_data, course_key):
        """
        Validates and returns the requested_user, while checking permissions.
        """
        requesting_user = self.initial['requesting_user']
        requested_username = cleaned_data.get('username', None)
        all_blocks = cleaned_data.get('all_blocks', False)

        if requested_username is None and not all_blocks:
            raise ValidationError({
                'username':
                ["This field is required unless all_blocks is requested."]
            })

        if requesting_user.is_anonymous:
            return self._verify_anonymous_user(requested_username, course_key,
                                               all_blocks)

        if all_blocks:
            if requesting_user.has_perm('instructor.research', course_key):
                return requesting_user
            return self._verify_all_blocks(requesting_user, course_key)
        elif requesting_user.username.lower() == requested_username.lower():
            return self._verify_requesting_user(requesting_user, course_key)
        else:
            return self._verify_other_user(requesting_user, requested_username,
                                           course_key)

    @staticmethod
    def _verify_anonymous_user(username, course_key, all_blocks):
        """
        Verifies form for when the requesting user is anonymous.
        """
        if all_blocks:
            raise PermissionDenied(
                "Anonymous users do not have permission to access all blocks in '{course_key}'."
                .format(course_key=str(course_key), ))

        # Check for '' and explicitly '' since the only valid option for anonymous users is
        # an empty string that corresponds to an anonymous user.
        if username != '':
            raise PermissionDenied(
                "Anonymous users cannot access another user's blocks.")

        if not permissions.is_course_public(course_key):
            raise PermissionDenied(
                "Course blocks for '{course_key}' cannot be accessed anonymously."
                .format(course_key=course_key, ))

        return AnonymousUser()

    @staticmethod
    def _verify_all_blocks(requesting_user, course_key):  # pylint: disable=useless-return
        """
        Verifies form for when no username is specified, including permissions.
        """
        # Verify all blocks can be accessed for the course.
        if not permissions.can_access_all_blocks(requesting_user, course_key):
            raise PermissionDenied(
                "'{requesting_username}' does not have permission to access all blocks in '{course_key}'."
                .format(
                    requesting_username=requesting_user.username,
                    course_key=str(course_key),
                ))

        return None

    @staticmethod
    def _verify_requesting_user(requesting_user, course_key):
        """
        Verifies whether the requesting user can access blocks in the course.
        """
        if not permissions.can_access_self_blocks(requesting_user, course_key):
            raise PermissionDenied(
                "Course blocks for '{requesting_username}' cannot be accessed."
                .format(requesting_username=requesting_user.username, ))
        return requesting_user

    @staticmethod
    def _verify_other_user(requesting_user, requested_username, course_key):
        """
        Verifies whether the requesting user can access another user's view of
        the blocks in the course.
        """
        # If accessing a public course, and requesting only content available publicly,
        # we can allow the request.
        if requested_username == '' and permissions.is_course_public(
                course_key):
            return AnonymousUser()

        # Verify requesting user can access the user's blocks.
        if not permissions.can_access_others_blocks(requesting_user,
                                                    course_key):
            raise PermissionDenied(
                "'{requesting_username}' does not have permission to access view for '{requested_username}'."
                .format(
                    requesting_username=requesting_user.username,
                    requested_username=requested_username,
                ))

        # Verify user exists.
        try:
            return User.objects.get(username=requested_username)
        except User.DoesNotExist:
            raise Http404(  # lint-amnesty, pylint: disable=raise-missing-from
                "Requested user '{requested_username}' does not exist.".format(
                    requested_username=requested_username, ))
コード例 #19
0
ファイル: forms.py プロジェクト: sbonaime/NEMO
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['tool', 'content', 'staff_only']

    expiration = IntegerField(label="Expiration date", min_value=0)
コード例 #20
0
class SurveySettingForm(Form):
    title = CharField(required=True, min_length=1, max_length=30)
    count = IntegerField(required=False, min_value=0)
    surveyType = IntegerField(required=True, min_value=0, max_value=1)
    questionsStr = CharField(required=True)
    _id = CharField(max_length=24, min_length=24, required=False)
コード例 #21
0
ファイル: forms.py プロジェクト: Palanaeum/palanaeum
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['page_length'] = IntegerField(max_value=100, min_value=10)
コード例 #22
0
ファイル: test_i18n.py プロジェクト: guyi2020/blog
 class CopyForm(Form):
     degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
コード例 #23
0
ファイル: forms.py プロジェクト: Palanaeum/palanaeum
class ImageConfig(Form):
    image_size_limit = IntegerField(min_value=1,
                                    max_value=20,
                                    label=_('Image size limit'),
                                    help_text=_('In megabytes'))
コード例 #24
0
class CommentForm(ModelForm):
    signed_fields = ['config_id', 'page_id', 'page_type']
    config_id = IntegerField(widget=SignedHiddenInput)
    body = CharField(
        widget=Textarea(attrs={'rows': settings.COMMENT_TEXTAREA_ROWS}),
        label=_('Your comment'),
        min_length=settings.MIN_LENGTH_COMMENT_BODY,
        max_length=settings.MAX_LENGTH_COMMENT_BODY)

    def __init__(self, data=None, **kwargs):
        self.request = kwargs.pop('request', None)
        # data = self.signer_fields(data, 'unsign')
        # kwargs['initial'] = self.signer_fields(kwargs.get('initial', {}))
        super(CommentForm, self).__init__(data, **kwargs)

    def security_validations(self):
        if Comment.objects.filter(user_ip=get_client_ip(self.request),
                                  created_at__gte=datetime.datetime.now() - datetime.timedelta(
                                      seconds=settings.COMMENT_WAIT_SECONDS)).count() \
                and settings.COMMENT_WAIT_SECONDS and not getattr(self.request, 'is_test', False):
            raise ValidationError(_('You must wait to post a new comment.'))

    def clean(self):
        cleaned_data = super(CommentForm, self).clean()
        if self.request and not is_staff(self.request):
            self.security_validations()
        return cleaned_data

    def clean_body(self):
        body = self.cleaned_data['body']
        if not is_staff(self.request):
            if settings.MAX_BREAKLINES_COMMENT_BODY and len(
                    body.split('\n')) > settings.MAX_BREAKLINES_COMMENT_BODY:
                raise ValidationError(
                    _('Your comment has too many line breaks.'))
            if settings.MAX_UPPERCASE_RATIO_COMMENT_BODY and sum(1 for c in body if c.isupper()) / (len(body) * 1.0) > \
                    settings.MAX_UPPERCASE_RATIO_COMMENT_BODY:
                raise ValidationError(
                    _('Your comment has too many uppercase letters.'))
        return body

    def save(self, commit=True, author=None):
        author = author or self.request.user
        user_agent = self.request.META.get('HTTP_USER_AGENT', 'unknown')
        referrer = self.request.META.get('HTTP_REFERER', '')
        user_ip = get_client_ip(self.request)
        published = settings.COMMENT_PUBLISHED_BY_DEFAULT
        is_spam = False
        if is_staff(self.request):
            # Always published for admins
            published = True
        else:
            is_spam = get_spam_protection().check(
                author,
                author.email,
                self.cleaned_data['body'],
                user_ip,
                user_agent,
                url=getattr(author, 'website', None),
                referrer='unknown',
                blog_domain=self.request.get_host())
            published = published and not is_spam
        comment = Comment(author=author,
                          user_ip=user_ip,
                          user_agent=user_agent,
                          referrer=referrer,
                          published=published,
                          config=CommentsConfig.objects.get(
                              pk=self.cleaned_data['config_id']),
                          **dict((key, self.cleaned_data[key])
                                 for key in ['body', 'page_id', 'page_type']))
        if is_spam:
            comment.requires_attention = 'spam'
            comment.moderated = 'spam'
        elif not published:
            comment.requires_attention = 'created'
        if commit:
            comment.save()
        return comment

    class Meta:
        widgets = {
            'page_id': SignedHiddenInput,
            'page_type': SignedHiddenInput,
        }
        model = Comment
        fields = ('body', 'page_type', 'page_id', 'config_id')
コード例 #25
0
class ImageEditForm(Form):
    height = IntegerField()
    width = IntegerField()
コード例 #26
0
ファイル: forms.py プロジェクト: Penguin2600/djangoTenK
class ExportForm(Form):
    starting_bib = IntegerField()
    ending_bib = IntegerField()
    export_set = ModelChoiceField(queryset=ExportSet.objects.all())
コード例 #27
0
 def add(x: IntegerField(), y: IntegerField()):
     return x + y
コード例 #28
0
 def test_integerfield_unicode_number(self):
     f = IntegerField()
     self.assertEqual(50, f.clean('50'))
コード例 #29
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        if self.request is None:
            raise ValueError("'request' kwargs is required.")
        self.pod = kwargs.pop("pod", None)
        if self.pod is None:
            raise ValueError("'pod' kwargs is required.")
        super(ComposeMachineForm, self).__init__(*args, **kwargs)

        # Build the fields based on the pod and current pod hints.
        self.fields["cores"] = IntegerField(min_value=1,
                                            max_value=self.pod.hints.cores,
                                            required=False)
        self.initial["cores"] = 1
        self.fields["memory"] = IntegerField(min_value=1024,
                                             max_value=self.pod.hints.memory,
                                             required=False)
        self.initial["memory"] = 1024
        self.fields["architecture"] = ChoiceField(
            choices=[(arch, arch) for arch in self.pod.architectures],
            required=False,
        )
        self.initial["architecture"] = self.pod.architectures[0]
        if self.pod.hints.cpu_speed > 0:
            self.fields["cpu_speed"] = IntegerField(
                min_value=300,
                max_value=self.pod.hints.cpu_speed,
                required=False,
            )
        else:
            self.fields["cpu_speed"] = IntegerField(min_value=300,
                                                    required=False)

        def duplicated_hostname(hostname):
            if Node.objects.filter(hostname=hostname).exists():
                raise ValidationError(
                    'Node with hostname "%s" already exists' % hostname)

        self.fields["hostname"] = CharField(
            required=False,
            validators=[duplicated_hostname, validate_hostname])
        self.initial["hostname"] = make_unique_hostname()
        self.fields["domain"] = ModelChoiceField(required=False,
                                                 queryset=Domain.objects.all())
        self.initial["domain"] = Domain.objects.get_default_domain()
        self.fields["zone"] = ModelChoiceField(required=False,
                                               queryset=Zone.objects.all())
        self.initial["zone"] = Zone.objects.get_default_zone()
        self.fields["pool"] = ModelChoiceField(
            required=False, queryset=ResourcePool.objects.all())
        self.initial["pool"] = self.pod.pool
        self.fields["storage"] = CharField(validators=[storage_validator],
                                           required=False)
        self.initial["storage"] = "root:8(local)"
        self.fields["interfaces"] = LabeledConstraintMapField(
            validators=[interfaces_validator],
            label="Interface constraints",
            required=False,
        )
        self.initial["interfaces"] = None
        self.fields["skip_commissioning"] = BooleanField(required=False)
        self.initial["skip_commissioning"] = False
        self.allocated_ips = {}
コード例 #30
0
ファイル: admin.py プロジェクト: vymana/turkle
class BatchForm(ModelForm):
    csv_file = FileField(label='CSV File')

    # Allow a form to be submitted without an 'allotted_assignment_time'
    # field.  The default value for this field will be used instead.
    # See also the function clean_allotted_assignment_time().
    allotted_assignment_time = IntegerField(
        initial=Batch._meta.get_field('allotted_assignment_time').get_default(),
        required=False)

    worker_permissions = ModelMultipleChoiceField(
        label='Worker Groups with access to this Batch',
        queryset=Group.objects.all(),
        required=False,
        widget=FilteredSelectMultiple('Worker Groups', False),
    )

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

        self.fields['allotted_assignment_time'].label = 'Allotted assignment time (hours)'
        self.fields['allotted_assignment_time'].help_text = 'If a user abandons a Task, ' + \
            'this determines how long it takes until their assignment is deleted and ' + \
            'someone else can work on the Task.'
        self.fields['csv_file'].help_text = 'You can Drag-and-Drop a CSV file onto this ' + \
            'window, or use the "Choose File" button to browse for the file'
        self.fields['csv_file'].widget = CustomButtonFileWidget(attrs={
            'class': 'hidden',
            'data-parsley-errors-container': '#file-upload-error',
        })
        self.fields['custom_permissions'].label = 'Restrict access to specific Groups of Workers '
        self.fields['project'].label = 'Project'
        self.fields['name'].label = 'Batch Name'

        self.fields['active'].help_text = 'Workers can only access a Batch if both the Batch ' + \
            'itself and the associated Project are Active.'

        if self.instance._state.adding and 'project' in self.initial:
            # We are adding a new Batch where the associated Project has been specified.
            # Per Django convention, the project ID is specified in the URL, e.g.:
            #   /admin/turkle/batch/add/?project=94

            # NOTE: The fields that are initialized here should match the fields copied
            #       over by the batch.copy_project_permissions() function.

            project = Project.objects.get(id=int(self.initial['project']))
            self.fields['custom_permissions'].initial = project.custom_permissions
            self.fields['login_required'].initial = project.login_required

            # Pre-populate permissions using permissions from the associated Project
            initial_ids = [str(id)
                           for id in get_groups_with_perms(project).values_list('id', flat=True)]
        else:
            # Pre-populate permissions
            initial_ids = [str(id)
                           for id in get_groups_with_perms(self.instance).
                           values_list('id', flat=True)]
        self.fields['worker_permissions'].initial = initial_ids

        # csv_file field not required if changing existing Batch
        #
        # When changing a Batch, the BatchAdmin.get_fields()
        # function will cause the form to be rendered without
        # displaying an HTML form field for the csv_file field.  I was
        # running into strange behavior where Django would still try
        # to validate the csv_file form field, even though there was
        # no way for the user to provide a value for this field.  The
        # two lines below prevent this problem from occurring, by
        # making the csv_file field optional when changing
        # a Batch.
        if not self.instance._state.adding:
            self.fields['csv_file'].required = False
            self.fields['project'].widget = \
                ProjectNameReadOnlyWidget(self.instance.project)

    def clean(self):
        """Verify format of CSV file

        Verify that:
        - fieldnames in CSV file are identical to fieldnames in Project
        - number of fields in each row matches number of fields in CSV header
        """
        cleaned_data = super().clean()

        csv_file = cleaned_data.get("csv_file", False)
        project = cleaned_data.get("project")

        if not csv_file or not project:
            return

        validation_errors = []

        # django InMemoryUploadedFile returns bytes and we need strings
        rows = csv.reader(StringIO(csv_file.read().decode('utf-8')))
        header = next(rows)

        csv_fields = set(header)
        template_fields = set(project.fieldnames)
        if csv_fields != template_fields:
            template_but_not_csv = template_fields.difference(csv_fields)
            if template_but_not_csv:
                validation_errors.append(
                    ValidationError(
                        'The CSV file is missing fields that are in the HTML template. '
                        'These missing fields are: %s' %
                        ', '.join(template_but_not_csv)))

        expected_fields = len(header)
        for (i, row) in enumerate(rows):
            if len(row) != expected_fields:
                validation_errors.append(
                    ValidationError(
                        'The CSV file header has %d fields, but line %d has %d fields' %
                        (expected_fields, i+2, len(row))))

        if validation_errors:
            raise ValidationError(validation_errors)

        # Rewind file, so it can be re-read
        csv_file.seek(0)

    def clean_allotted_assignment_time(self):
        """Clean 'allotted_assignment_time' form field

        - If the allotted_assignment_time field is not submitted as part
          of the form data (e.g. when interacting with this form via a
          script), use the default value.
        - If the allotted_assignment_time is an empty string (e.g. when
          submitting the form using a browser), raise a ValidationError
        """
        data = self.data.get('allotted_assignment_time')
        if data is None:
            return Batch._meta.get_field('allotted_assignment_time').get_default()
        elif data.strip() == '':
            raise ValidationError('This field is required.')
        else:
            return data
コード例 #31
0
class Choice(Form):
    choice = CharField()
    votes = IntegerField()
コード例 #32
0
ファイル: forms.py プロジェクト: biogluck/bookshop
class AddToCartSessionForm(Form):
    quantity = IntegerField()
    update = BooleanField(required=False, initial=False, widget=HiddenInput)
コード例 #33
0
ファイル: forms.py プロジェクト: aderoin/server
class SendMissionForm(Form):
    robot_uuid = UUIDField()
    mission_id = IntegerField()
コード例 #34
0
ファイル: test_regressions.py プロジェクト: LucasNoga/Python
 class HiddenForm(Form):
     data = IntegerField(widget=HiddenInput)
コード例 #35
0
 def test_integerfield_big_num(self):
     f = IntegerField()
     self.assertEqual(9223372036854775808, f.clean(9223372036854775808))
     self.assertEqual(9223372036854775808, f.clean('9223372036854775808'))
     self.assertEqual(9223372036854775808, f.clean('9223372036854775808.0'))
コード例 #36
0
class NoteDeleteForm(Form):
    note = IntegerField(widget=HiddenInput())
コード例 #37
0
 def test_integerfield_2(self):
     f = IntegerField(required=False)
     self.assertIsNone(f.clean(''))
     self.assertEqual('None', repr(f.clean('')))
     self.assertIsNone(f.clean(None))
     self.assertEqual('None', repr(f.clean(None)))
     self.assertEqual(1, f.clean('1'))
     self.assertIsInstance(f.clean('1'), int)
     self.assertEqual(23, f.clean('23'))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('a')
     self.assertEqual(1, f.clean('1 '))
     self.assertEqual(1, f.clean(' 1'))
     self.assertEqual(1, f.clean(' 1 '))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('1a')
     self.assertIsNone(f.max_value)
     self.assertIsNone(f.min_value)
コード例 #38
0
ファイル: viewsets.py プロジェクト: allengosta/some_tests
    def list(self, request, *args, **kwargs):
        call_center_primary_visits_whens = []
        managers_outcome_calls_whens = []
        call_center_working_specs_whens = []

        if self.kwargs['id'] != '0':
            project_id = self.kwargs['id']
            project = Project.objects.get(id=project_id)
            check_date_str = request.query_params.get('check_date', None)

            check_date = datetime.strptime(check_date_str,
                                           "%Y-%m-%dT%H:%M:%S.%f")

            primary_income_calls_query = Q(
                contacts__time__date=check_date.date()) & Q(
                    contacts__source__in=[2, 3],
                    contacts__extra_type=0) & Q(contacts__typex=1)

            managers_outcome_calls = Contact.objects.filter(Q(project=project_id) if project_id else Q(),
                                                            extra_type__in=(0, 1),
                                                            source=2,
                                                            typex=0,
                                                            time__date=check_date.date()). \
                exclude(user__user_permissions__name='operator').exclude(result__in=(9,))

            call = Contact.objects.filter(
                client=OuterRef('client'),
                extra_type__in=(0, 1),
                user__user_permissions__name='operator')

            call_center_primary_visits_query = Contact.objects.filter(
                Q(project=project_id) if project_id else Q(),
                source=1,
                time__date=check_date.date(),
                client__contacts__extra_type__in=(0, 1),
                # user__user_permissions__name='operator',
                client__contacts__time__lte=F('time'),
                client__contacts__time__gte=F('time') -
                Interval(Value('1 month'))).annotate(
                    calls_q=Exists(call)).filter(
                        calls_q=True).distinct('client').filter(
                            extra_type__in=[0, 2, 3])

            call_center_primary_visits_count = call_center_primary_visits_query.count(
            )
            call_center_primary_visits_whens.append(
                When(id=project.id, then=call_center_primary_visits_count))

            managers_outcome_calls_count = managers_outcome_calls.count()
            managers_outcome_calls_whens.append(
                When(id=project.id, then=managers_outcome_calls_count))

            self.queryset = self.queryset.annotate(
                primary_income_calls=Count(Case(
                    When(primary_income_calls_query,
                         then=F('contacts__client'))),
                                           distinct=True),
                call_center_working_specs=Case(
                    *call_center_working_specs_whens,
                    default=0,
                    output_field=IntegerField()),
                call_center_primary_visits=Case(
                    *call_center_primary_visits_whens,
                    default=0,
                    output_field=IntegerField()),
                managers_outcome_calls=Case(*managers_outcome_calls_whens,
                                            default=0,
                                            output_field=IntegerField()),
            )
            return super().list(request, *args, **kwargs)
コード例 #39
0
 def test_integerfield_1(self):
     f = IntegerField()
     self.assertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" required>')
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean(None)
     self.assertEqual(1, f.clean('1'))
     self.assertIsInstance(f.clean('1'), int)
     self.assertEqual(23, f.clean('23'))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('a')
     self.assertEqual(42, f.clean(42))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean(3.14)
     self.assertEqual(1, f.clean('1 '))
     self.assertEqual(1, f.clean(' 1'))
     self.assertEqual(1, f.clean(' 1 '))
     with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
         f.clean('1a')
     self.assertIsNone(f.max_value)
     self.assertIsNone(f.min_value)
コード例 #40
0
    class UserForm(CrispyModelForm):

        name_required = False
        if dynamic_model == Teacher:
            name_required = True

        first_name = CharField(max_length=256, required=name_required)
        last_name = CharField(max_length=256, required=name_required)
        if dynamic_model == Student:
            student_id = IntegerField(validators=[student_id_validator], required=False)
            class_standing = ChoiceField(choices=YEAR_IN_SCHOOL_CHOICES, required=False)
        email = EmailField()

        def clean(self):
            cleaned_data = super().clean()
            last_name = cleaned_data.get("last_name")
            first_name = cleaned_data.get("first_name")
            email = cleaned_data.get("email")
            if any(i.isdigit() for i in first_name):
                raise ValidationError("First Name must contain only characters.")
            elif any(i.isdigit() for i in last_name):
                raise ValidationError("Last Name must contain only characters.")
            if not self.instance.id:
                if BaseUser.objects.filter(username=email).exists():
                    raise ValidationError("Email is already registered. Please use a different email.")
                elif BaseUser.objects.filter(email=email).exists():
                    raise ValidationError("Email is already registered. Please use a different email.")
                elif BaseUser.objects.filter(username=email.split('@')[0]).exists():
                    raise ValidationError("Email is already registered. Please use a different email.")
            return cleaned_data

        def save(self, **kwargs):
            cleaned_data = self.cleaned_data
            """
            The instance ID exists only in an edit form, so this way we know we are updating and not creating an object
            """
            if self.instance.id is not None:
                if dynamic_model == Student:
                    student = Student.objects.filter(pk=self.instance.id)
                    user_object = BaseUser.objects.filter(pk=student[0].user_id)

                    user_object.update(
                        username=cleaned_data.get("email").split("@")[0],
                        email=cleaned_data.get("email"),
                        first_name=cleaned_data.get("first_name"),
                        last_name=cleaned_data.get("last_name")
                    )
                    student.update(
                        student_id=cleaned_data.get("student_id"),
                        class_standing=cleaned_data.get("class_standing"),
                    )
                elif dynamic_model == Teacher:
                    teacher = Teacher.objects.filter(pk=self.instance.id)
                    user_object = BaseUser.objects.filter(pk=teacher[0].user_id)
                    user_object.update(
                        username=cleaned_data.get("email").split("@")[0],
                        email=cleaned_data.get("email"),
                        first_name=cleaned_data.get("first_name"),
                        last_name=cleaned_data.get("last_name")
                    )
                    teacher.update(
                        department=cleaned_data.get("department")
                    )
            else:
                if dynamic_model == Student:
                    user_object = BaseUser(
                        username=cleaned_data.get("email").split("@")[0],
                        email=cleaned_data.get("email"),
                        password=BaseUser.objects.make_random_password(),
                        first_name=cleaned_data.get("first_name"),
                        last_name=cleaned_data.get("last_name")
                    )
                    student = Student(
                        student_id=cleaned_data.get("student_id"),
                        class_standing=cleaned_data.get("class_standing"),
                        user=user_object,
                        user_id=user_object.id
                    )
                    user_object.save()
                    student.save()
                else:
                    user_object = BaseUser(
                        username=cleaned_data.get("email").split("@")[0],
                        email=cleaned_data.get("email"),
                        password=BaseUser.objects.make_random_password(),
                        first_name=cleaned_data.get("first_name"),
                        last_name=cleaned_data.get("last_name")
                    )
                    teacher = Teacher(
                        user=user_object,
                        user_id=user_object.id,
                        department=cleaned_data.get("department")
                    )
                    user_object.save()
                    teacher.save()

        class Meta:
            model = dynamic_model
            exclude = ['user', 'registrations', 'student_id', 'first_name', 'last_name', 'class_standing']
            if dynamic_model == Teacher:
                exclude = ['user', 'registrations']

            field_order = [
                'first_name',
                'last_name',
                'email',
                'class_standing',
                'student_id',
                'registrations',
                'overseeing_department'
            ]
            labels = label_dict