예제 #1
0
class TableCollapseForm(forms.Form):
    count_matrix = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Count Matrix",
        widget=autocomplete.ModelSelect2(url='result-countmatrix-autocomplete',
                                         forward=("taxonomy_result", ),
                                         attrs={
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             'data-html': True,
                                             'data-allow-clear': 'true'
                                         }))
    taxonomy_result = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Taxonomic Classification Set",
        widget=autocomplete.ModelSelect2(url='result-taxonomy-autocomplete',
                                         forward=("count_matrix", ),
                                         attrs={
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             'data-html': True,
                                             'data-allow-clear': 'true'
                                         }))

    normalize_methods = ["raw", "counts", "none", "proportion", "percent"]
    normalize_method = autocomplete.Select2ListChoiceField(
        choice_list=normalize_methods,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "proportion",
                'data-html': True
            }))

    tax_ranks = [
        "Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species",
        "Full"
    ]
    taxonomic_level = autocomplete.Select2ListChoiceField(
        choice_list=tax_ranks,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "Genus",
                'data-html': True
            }))
    metadata_collapse = forms.ModelChoiceField(
        queryset=DataSignature.objects.all(),
        label="Metadata for Aggregation",
        required=False,
        widget=autocomplete.ModelSelect2(url='sample-metadata-autocomplete',
                                         forward=("count_matrix", ),
                                         attrs={
                                             "data-allow-clear": "true",
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             "data-html": True
                                         }))
    def test_init(self):
        field = autocomplete.Select2ListChoiceField(
            choice_list=self.choice_list)
        six.assertCountEqual(self, field.choices,
                             [(choice, choice) for choice in self.choice_list])

        field = autocomplete.Select2ListChoiceField(
            choice_list=self.get_choice_list)
        six.assertCountEqual(self, field.choices,
                             [(choice, choice) for choice in self.choice_list])
    def test_init_tuples(self):
        field = autocomplete.Select2ListChoiceField(
            choice_list=self.choice_list_tuples)
        six.assertCountEqual(self, field.choices,
                             [(value, text)
                              for [value, text] in self.choice_list_tuples])

        field = autocomplete.Select2ListChoiceField(
            choice_list=self.get_choice_list_tuples)
        six.assertCountEqual(self, field.choices,
                             [(value, text)
                              for [value, text] in self.choice_list_tuples])
예제 #4
0
	def __init__(self, tup, *args, **kwargs):
		# extra_fields = kwargs.pop('extra', 0)
		super(AddEntryForm, self).__init__(*args, **kwargs)
		self.fields['courses'] = autocomplete.Select2ListChoiceField(
        choice_list=tup,
        widget=autocomplete.ListSelect2(url=None)
    )
예제 #5
0
class SearchForm(forms.Form):
    OPERATION_CHOICES = (
        ('CONTAINS', 'CONTAINS'),
        # ('DOES NOT CONTAIN', 'DOES NOT CONTAIN'),
        ('EQUALS', 'EQUALS'),
        # ('DOES NOT EQUAL', 'DOES NOT EQUAL')  # TODO: Figure out how to implement these with the .filter
        ('LESS THAN', 'LESS THAN'),
        ('GREATER THAN', 'GREATER THAN'),
        ('BEFORE', 'BEFORE'),
        ('AFTER', 'AFTER'),
    )

    AND_OR_CHOICES = (('AND', 'AND'), ('OR', 'OR'))
    search_attribute = autocomplete.Select2ListChoiceField(
        choice_list=make_list_of_fields,
        widget=autocomplete.ListSelect2(
            url='data_wrapper:attribute-autocomplete'),
        required=True)
    search_item = forms.CharField(label='Search term',
                                  max_length=100,
                                  required=False)
    operation = forms.ChoiceField(
        choices=OPERATION_CHOICES,
        widget=forms.Select(attrs={'class': 'operation_choice'}))
    combine_choice = forms.ChoiceField(choices=AND_OR_CHOICES)
    date_input = forms.DateField(
        widget=forms.TextInput(attrs={'class': 'datepicker'}), required=False)
예제 #6
0
class RevenueItemAdminForm(ModelForm):
    currentlyHeldBy = ModelChoiceField(
        queryset=User.objects.filter(
            Q(staffmember__isnull=False) | Q(is_staff=True)),
        label=_('Cash currently in possession of'),
        required=False,
        widget=autocomplete.ModelSelect2(
            url='autocompleteUser',
            attrs={
                # This will set the input placeholder attribute:
                'data-placeholder': _('Enter a user name'),
                # This will set the yourlabs.Autocomplete.minimumCharacters
                # options, the naming conversion is handled by jQuery
                'data-minimum-input-length': 2,
                'data-max-results': 4,
                'class': 'modern-style',
            }))
    paymentMethod = autocomplete.Select2ListChoiceField(
        choice_list=get_method_list,
        required=False,
        widget=autocomplete.ListSelect2(url='paymentMethod-list-autocomplete'))

    class Meta:
        model = RevenueItem
        exclude = []
예제 #7
0
class ExpenseItemAdminForm(ModelForm):
    payToUser = ModelChoiceField(
        queryset=User.objects.all(),
        label=_('Pay to this user'),
        required=False,
        widget=autocomplete.ModelSelect2(
            url='autocompleteUser',
            attrs={
                # This will set the input placeholder attribute:
                'data-placeholder': _('Enter a user name'),
                # This will set the yourlabs.Autocomplete.minimumCharacters
                # options, the naming conversion is handled by jQuery
                'data-minimum-input-length': 2,
                'data-max-results': 4,
                'class': 'modern-style',
            }))
    paymentMethod = autocomplete.Select2ListChoiceField(
        choice_list=get_method_list,
        required=False,
        widget=autocomplete.ListSelect2(url='paymentMethod-list-autocomplete'))

    class Meta:
        model = ExpenseItem
        exclude = []
        widgets = {'category': ExpenseCategoryWidget}
예제 #8
0
class ParkingTicketForm(forms.ModelForm):
    day_of_week = autocomplete.Select2ListChoiceField(
        choice_list=list(calendar.day_name)
    )  #, widget=autocomplete.ListSelect2(url='dsp:ptform-options-autocomplete'))
    week_of_month = autocomplete.Select2ListChoiceField(
        choice_list=['1st', '2nd', '3rd', '4th']
    )  #, widget=autocomplete.ListSelect2(url='dsp:ptform-options-autocomplete'))

    class Meta:
        model = PTFormInput
        fields = (
            'week_of_month',
            'day_of_week',
        )
        widgets = {
            'week_of_month':
            autocomplete.ListSelect2(url='dsp:ptform-options-autocomplete'),
            'day_of_week':
            autocomplete.ListSelect2(url='dsp:ptform-options-autocomplete'),
        }
예제 #9
0
class CustomTableForm(forms.Form):
    table_attribute = autocomplete.Select2ListChoiceField(
        choice_list=make_list_of_fields,
        widget=autocomplete.ListSelect2(
            url='data_wrapper:attribute-autocomplete'),
        required=True)
    # Apparently when a form is completely blank in a formset, Django skips doing validation of it.
    # My hacky solution: Create another attribute to the form that defaults to a non-blank value, forcing
    # validation of the blank attribute. This hidden attribute is never displayed to the user.
    # A quick google didn't turn up a better way to solve the problem, but a better solution does probably exist.
    hidden_attribute = forms.CharField(max_length=1,
                                       required=False,
                                       empty_value='a')
예제 #10
0
class WalletPlanningForm(forms.Form):
    ticker = autocomplete.Select2ListChoiceField(
        choice_list=tickerData.getTickerList,
        widget=autocomplete.ListSelect2(
            url='stock-autocomplete',
            attrs={
                'class':'form-control p-0 m-0 border border-primary',
                'data-minimum-input-length': 3
            }
        )
    )
    quantity = forms.FloatField(
        required=True, label='Quantidade',
        min_value=0,
        initial=0,
        widget=forms.NumberInput(
            attrs={
                'class':'form-control form-control-sm border border-primary',
                'step': '1'
            }
        )
    )
    percent = forms.FloatField(
        label='Porcentagem',
        required=False, 
        min_value=0.00,
        widget=forms.NumberInput(
            attrs={
                'class':'form-control form-control-sm border border-primary',
                'step': '0.01'
            }
        )
    )
    
    def clean_ticker(self):
        ticker = self.cleaned_data['ticker']
        if ticker not in tickerData.getTickerList():
            self.add_error(
                'ticker',
                'Ticker inválido'
            )
        else:
            data = tickerData.getTickerInfo(ticker)
            if data:
                ticker = data  
            else:
                self.add_error(
                    'ticker',
                    'Ticker possui informações incompletas'
                )
        return ticker
예제 #11
0
class MetaDataRequestForm(forms.Form):
    genus = autocomplete.Select2ListChoiceField(
        choice_list=make_genus_choice_list,
        widget=autocomplete.ListSelect2(url='metadata:genus_autocompleter'),
        required=False)
    species = autocomplete.Select2ListChoiceField(
        choice_list=make_species_choice_list,
        widget=autocomplete.ListSelect2(url='metadata:species_autocompleter'),
        required=False)
    serotype = autocomplete.Select2ListChoiceField(
        choice_list=make_serotype_choice_list,
        widget=autocomplete.ListSelect2(url='metadata:serotype_autocompleter'),
        required=False)
    mlst = autocomplete.Select2ListChoiceField(
        choice_list=make_mlst_choice_list,
        widget=autocomplete.ListSelect2(url='metadata:mlst_autocompleter'),
        required=False)
    rmlst = autocomplete.Select2ListChoiceField(
        choice_list=make_rmlst_choice_list,
        widget=autocomplete.ListSelect2(url='metadata:rmlst_autocompleter'),
        required=False)

    quality = forms.ChoiceField(choices=quality_choices)
class SignupFormCoordinator(forms.Form):

    def gen_choices():
        users = cache_fill()            
        return [ user['id'] for user in users ] 
    
    comment = forms.CharField(label='Comment', required=False)
    email = autocomplete.Select2ListChoiceField(
                required=False,
                choice_list=gen_choices,
                widget=autocomplete.ListSelect2(
                    url='email-autocomplete', 
                    attrs={'data-html': True},
                    ),
                )
예제 #13
0
class PCoAPlotForm(forms.Form):
    count_matrix = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Count Matrix",
        widget=autocomplete.ModelSelect2(url='result-countmatrix-autocomplete',
                                         forward=("taxonomy_result", ),
                                         attrs={
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             'data-html': True,
                                             'data-allow-clear': 'true'
                                         }))
    measures = [
        'euclidean', 'l2', 'l1', 'manhattan', 'cityblock', 'braycurtis',
        'canberra', 'chebyshev', 'correlation', 'cosine', 'dice', 'hamming',
        'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski',
        'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener',
        'sokalsneath', 'sqeuclidean', 'yule', 'wminkowski', 'nan_euclidean',
        'haversine'
    ]
    measure = autocomplete.Select2ListChoiceField(
        required=True,
        choice_list=measures,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "Select a distance/dissimilarity measure",
                'data-html': True
            }))
    metadata_colour = forms.ModelChoiceField(
        queryset=DataSignature.objects.all(),
        label="Metadata for Colour",
        required=False,
        widget=autocomplete.ModelSelect2(
            url='sample-metadata-autocomplete',
            forward=("count_matrix", ),
            attrs={
                "data-allow-clear": "true",
                "data-placeholder": "Select metadata to colour Samples by",
                "style": "flex-grow: 1; width: 50%",
                "data-html": True
            }))
    three_dimensional = forms.BooleanField(
        required=False,
        initial=False,
        label="3D Plot",
        widget=forms.CheckboxInput(attrs={"class": "big-checkbox"}))
예제 #14
0
class GallerySortForm(forms.Form):

    vr_choices = [(0, "None"), (1, '0-10'), (2, '10-30'), (3, '30-100'),
                  (4, '100-500'), (5, '500+')]
    ascending_choices = [(0, "Ascending time"), (1, "Descending time"),
                         (2, "Ascending visual Range"),
                         (3, "Descending visual Range")]

    ascending = forms.ChoiceField(ascending_choices,
                                  label="Order by:",
                                  widget=forms.Select())

    visual_range = forms.ChoiceField(
        choices=vr_choices,
        label="Visual Range(in Kilometers):",
        widget=forms.Select(attrs={
            'id': 'vr',
            'name': 'Visual Range(in meters)',
            'class': 'form-control'
        }))

    #auto complete on location
    location = autocomplete.Select2ListChoiceField(
        required=False,
        label="Location:",
        choice_list=getNames(),
        widget=autocomplete.ListSelect2(url='location-autocomplete'))

    date1 = forms.CharField(
        required=False,
        label="Beginning date",
        widget=forms.TextInput(attrs={
            'id': 'date1',
            'name': 'date-begin',
            'class': 'form-control'
        }))

    date2 = forms.CharField(
        required=False,
        label="End date",
        widget=forms.TextInput(attrs={
            'id': 'date2',
            'name': 'date-end',
            'class': 'form-control'
        }))
예제 #15
0
class InventoryitemForm(forms.ModelForm):
    class Meta:
        model = Inventoryitem
        fields = ('__all__')

    item_indate = forms.DateField(label='Date entered DB',
                                  initial=datetime.date.today)

    item_pickup = forms.ModelChoiceField(
        label='Pickup #',
        queryset=Pickup.objects.all(),
        widget=autocomplete.ModelSelect2(url='pickup-autocomplete'))

    #  item_category  = autocomplete.Select2ListCreateChoiceField(choice_list=None, widget=autocomplete.ListSelect2(url='category-autocomplete'))

    item_category = forms.ModelChoiceField(
        label='Item Category',
        queryset=Category.objects.only('category'),
        to_field_name='category',
        widget=autocomplete.ListSelect2(url='category-autocomplete'))

    item_segment = autocomplete.Select2ListCreateChoiceField(
        choice_list=Segment.objects.all(),
        widget=autocomplete.ListSelect2(url='segment-autocomplete',
                                        forward=['item_category']),
    )

    item_type = autocomplete.Select2ListCreateChoiceField(
        choice_list=Type.objects.all(),
        widget=autocomplete.ListSelect2(
            url='type-autocomplete', forward=['item_category',
                                              'item_segment']),
        required=False,
    )
    item_quantity = forms.IntegerField(initial=1, required=False)

    item_brand = autocomplete.Select2ListCreateChoiceField(
        choice_list=Brand.objects.all(),
        widget=autocomplete.ListSelect2(url='brand-autocomplete'),
        required=False,
    )

    item_size = autocomplete.Select2ListCreateChoiceField(
        choice_list=Size.objects.all(),
        widget=autocomplete.ListSelect2(
            url='size-autocomplete', forward=['item_category',
                                              'item_segment']),
        required=False,
    )

    item_color = forms.CharField(required=False, disabled=True)

    colors = forms.ModelMultipleChoiceField(
        queryset=Color.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url='color-autocomplete'),
        required=False)

    #    colors = forms.ModelMultipleChoiceField(queryset=Color.objects.all(), required=False)

    def get_firstassessment_choice_list():
        return ['Sale', 'Donation', 'Recycling']

    item_firstassessment = autocomplete.Select2ListChoiceField(
        choice_list=get_firstassessment_choice_list,
        widget=autocomplete.ListSelect2(url='firstassessment-autocomplete'))

    item_donationvalue = forms.DecimalField(min_value=0,
                                            decimal_places=2,
                                            required=False)

    def get_condition_choice_list():
        return [
            'New in a box', 'New w/o tags', 'New w tags', 'Like new',
            'Gently used', 'Used', 'w defect'
        ]

    item_condition = autocomplete.Select2ListChoiceField(
        choice_list=get_condition_choice_list,
        widget=autocomplete.ListSelect2(url='condition-autocomplete'),
        required=False)

    # cut = forms.ModelMultipleChoiceField(
    #     queryset= Cut.objects.all(),
    #     widget=forms.CheckboxSelectMultiple(),
    # )

    #    item_cut = autocomplete.Select2ListCreateChoiceField(choice_list=Cut.objects.all(), widget=autocomplete.ListSelect2(url='cut-autocomplete', forward=['itemtype']), required=False,)
    item_cut = forms.CharField(required=False, disabled=True)
    cuts = forms.ModelMultipleChoiceField(
        queryset=Cut.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url='cut-autocomplete',
                                                 forward=['itemtype']),
        required=False)
    item_style = forms.CharField(required=False, disabled=True)
    additional_info = forms.CharField(
        label='Additional information if necessary. Useful for unique items.',
        required=False,
        widget=forms.Textarea)

    #  item_fabric = autocomplete.Select2ListCreateChoiceField(choice_list=Fabric.objects.all(), widget=autocomplete.ListSelect2(url='fabric-autocomplete'), required=False, disabled=True)
    item_fabric = forms.CharField(required=False, disabled=True)

    item_usecase = forms.CharField(required=False, disabled=True)

    usecases = forms.ModelMultipleChoiceField(
        queryset=Usecase.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url='usecase-autocomplete'),
        required=False)

    item_postprice = forms.DecimalField(
        decimal_places=2,
        required=False,
    )
    item_origprice = forms.DecimalField(
        decimal_places=2,
        required=False,
    )

    def get_status_choice_list():
        return [
            'Ready4donation', 'Ready4sale', 'Ready4recycling', 'Donated',
            'Up4sale', 'Ready2ship', 'Shipped', 'Recycled', 'Treatment',
            'Returned', 'Lost', 'Sent2realreal', 'Soldonrealreal',
            'Soldonbuffxchange', 'Sent2consignment', 'Sent2revolve'
        ]

    item_status = autocomplete.Select2ListCreateChoiceField(
        choice_list=get_status_choice_list,
        widget=autocomplete.ListSelect2(url='status-autocomplete'))

    def get_customer_status_choice_list():
        return [
            'Ready for donation', 'Ready for sale', 'Ready for recycling',
            'Donated', 'Up for sale', 'Ready to ship', 'Shipped', 'Recycled',
            'Treatment'
        ]

    customerfacingstatus = autocomplete.Select2ListCreateChoiceField(
        label='Customer Facing Status',
        choice_list=get_customer_status_choice_list,
        widget=autocomplete.ListSelect2(url='customerstatus-autocomplete'))

    item_statuschangedate = forms.DateField(label='Status Changed',
                                            initial=datetime.date.today)
    item_location = forms.CharField(required=False, )

    def get_mktplace_choice_list():
        return ['Up', 'Down', 'Sold', 'Returned']

    ebay = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    poshmark = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    vinted = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    tradesy = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    craigslist = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    letgo = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    offerup = autocomplete.Select2ListChoiceField(
        choice_list=get_mktplace_choice_list,
        widget=autocomplete.ListSelect2(url='mktplace-autocomplete'),
        required=False,
    )
    offline = forms.ChoiceField(
        choices=[('', None), (1, 'Sold')],
        required=False,
    )

    def clean(self):
        cleaned_data = self.cleaned_data
        item_category = cleaned_data.get("item_category")
        db_value = Category.objects.get(category=item_category).category

        # if  db_value=='Clothes' or db_value=='Shoes' or db_value=='Accessories':
        #     # Keep the database consistent. The user may have
        #     # submitted a shipping_destination even if shipping
        #     # was not selected
        #     #self.cleaned_data['item_brand'] = ''
        #     if not cleaned_data['item_brand'] or not cleaned_data['item_size'] or not cleaned_data['item_color']:
        #         raise forms.ValidationError("'item_brand', 'item_size', and 'item_color' are required.")
        # else:
        #     cleaned_data['item_brand'] = ''
        #     cleaned_data['item_size'] = ''
        #     cleaned_data['item_color'] = ''

        if not cleaned_data['item_type']:
            if db_value == 'Clothes' or db_value == 'Shoes' or db_value == 'Accessories' or db_value == 'Electronics' or db_value == 'Toys' or db_value == 'Home' or db_value == 'SportsGear' or db_value == 'Cosmetics':
                raise forms.ValidationError("'item_type' is required.")

    #   if not cleaned_data['item_brand']:
    #       if  db_value=='Clothes' or db_value=='Shoes' or db_value=='Accessories' or db_value=='Electronics' or db_value=='Toys' or db_value=='Home' or db_value=='SportsGear' or db_value=='Cosmetics':
    #            raise forms.ValidationError("'item_brand' is required.")

        if not cleaned_data['item_size']:
            if db_value == 'Clothes' or db_value == 'Shoes':
                raise forms.ValidationError("'item_size' is required.")

    #  item_color=cleaned_data.get('item_color')
    #  item_color1=cleaned_data['item_color']
    #  color = Color.objects.get(color=item_color1).color

    #if not cleaned_data['colors']:
    #      if  db_value=='Clothes' or db_value=='Shoes':
    #          raise forms.ValidationError("'item_color' is required.")

    #item_id = cleaned_data.get('id')
    #item_status = cleaned_data.get('item_status')
    #item_status_val = Inventoryitem.objects.get(id=item_id).item_status
    #poshmark = cleaned_data.get('poshmark')
    #ebay =cleaned_data.get('ebay')
    #vinted =cleaned_data.get('vinted')
    #tradesy =cleaned_data.get('tradesy')
    #craigslist =cleaned_data.get('craigslist')
    #offerup =cleaned_data.get('offerup')
    #letgo =cleaned_data.get('letgo')

    #   if item_status_val=='Shipped':
    #       if (poshmark=='up' or ebay=='up' or vinted=='up' or tradesy=='up' or craigslist=='up' or offerup=='up' or letgo=='up') :
    #           raise ValidationError("cant change status for shipping when 'Up' on one of the platforms")

        return self.cleaned_data

    def __init__(self, *args, **kwargs):
        #   self.id = kwargs.pop('id')
        super(InventoryitemForm, self).__init__(auto_id=True, *args, **kwargs)
class AllocationForm(forms.ModelForm):
    unit_value = forms.DecimalField(
        label="Unit Value",
        widget=forms.TextInput(attrs={
            "style": "width:100px",
            "mask": "#,##0.00",
            "placeholder": ""
        }))
    stock = autocomplete.Select2ListChoiceField(
        widget=autocomplete.ListSelect2(url='stock-autocomplete',
                                        attrs={
                                            'data-minimum-input-length': 3,
                                            'class': 'form-control'
                                        }))
    total = forms.CharField(
        label="Total",
        widget=forms.TextInput(attrs={
            "style": "width:100px",
            "mask": "#,##0.00",
            "placeholder": ""
        }))
    percentage = forms.IntegerField(
        label="Percentage",
        widget=forms.TextInput(attrs={
            "style": "width:100px",
            "mask": "999",
            "placeholder": ""
        }))
    quantity = forms.IntegerField(
        label="Quantity",
        widget=forms.TextInput(attrs={
            "style": "width:100px",
            "mask": "#,##0.00",
            "placeholder": ""
        }))

    def __init__(self, *args, **kwargs):
        super(AllocationForm, self).__init__(*args, **kwargs)
        #The quantity, unit_value and total are automatically filled
        self.fields['quantity'].widget.attrs['disabled'] = True
        self.fields['total'].widget.attrs['disabled'] = True
        self.fields['unit_value'].widget.attrs['disabled'] = True

        if self.instance.pk:
            self.fields['stock'].choices = [(self.instance.stock,
                                             self.instance.stock)]

    def clean(self):
        #when using the autocomplete library the stock value is not in the self.cleaned_data variable
        if self.data.get("%s-stock" % (self.prefix), None):
            stock = self.data["%s-stock" % (self.prefix)]

            #Validate if the stock informed exist
            response = requests.get(
                get_api_url("stock_search") +
                "&search_term=%s&search_by=symbol&limit=50&page=1" % stock)
            json_response = json.loads(response.text)

            #the method clean_stock is not callend when using the autocomplete libray
            if json_response.get("total_returned") == 0:
                self.errors["stock"][0] = "Stock symbol is not valid."
                raise forms.ValidationError("Stock symbol is not valid.")
            else:
                self.fields['stock'].choices = [(stock, stock)]
                self.cleaned_data["stock"] = stock
                if self.errors.get("stock", None):
                    del self.errors["stock"]

        return self.cleaned_data

    def clean_total(self):
        total = Decimal(self.cleaned_data["total"].replace(",", ""))
        unit_value = self.cleaned_data["unit_value"]
        quantity = self.cleaned_data["quantity"]
        correct_total = unit_value * quantity

        if total != correct_total:
            raise forms.ValidationError("The total should be %s, %s found." %
                                        (correct_total, total))

        return total

    def clean_percentage(self):
        percentage = self.cleaned_data["percentage"]

        if percentage > 100:
            raise forms.ValidationError(
                "The percentage should be between 0 and 100.")

        return percentage

    class Meta:
        model = Allocation
        exclude = ()
예제 #17
0
class MakeForm(forms.ModelForm):
    make = forms.ChoiceField(choices=MAKES)
    model = autocomplete.Select2ListChoiceField(
        choice_list=get_model_list,
        widget=autocomplete.ListSelect2(url='model-list-autocomplete',
                                        forward=['make']))
예제 #18
0
class LocationForm(happyforms.ModelForm):
    """Form to provide location data."""

    timezone = autocomplete.Select2ListChoiceField(
        choice_list=get_timezones_list,
        required=False,
        widget=autocomplete.ListSelect2(url='users:timezone-autocomplete',
                                        forward=['country', 'city', 'region']))

    def __init__(self, *args, **kwargs):
        """Override init method.

        Make country a required field.
        """
        super(LocationForm, self).__init__(*args, **kwargs)
        self.fields['country'].required = True
        if self.data and (self.data.get('city') or self.data.get('country')):
            self.fields['country'].required = False

    def clean(self):
        """Override clean method.

        We need at least the country of the user.
        If a user supplies a city or a region, we can extract
        the data from there.
        """
        super(LocationForm, self).clean()

        country = self.cleaned_data.get('country')
        region = self.cleaned_data.get('region')
        city = self.cleaned_data.get('city')

        if not city and not country and not region:
            msg = _(u'Please supply your location data.')
            raise forms.ValidationError(msg)

        if region:
            self.cleaned_data['country'] = region.country

        if city:
            self.cleaned_data['country'] = city.country
            self.cleaned_data['region'] = city.region

        return self.cleaned_data

    class Meta:
        model = UserProfile
        fields = (
            'timezone',
            'privacy_timezone',
            'city',
            'privacy_city',
            'region',
            'privacy_region',
            'country',
            'privacy_country',
        )
        widgets = {
            'country':
            autocomplete.ModelSelect2(url='users:country-autocomplete',
                                      attrs={
                                          'data-placeholder':
                                          u'Start typing to select a country.',
                                          'data-minimum-input-length': 2
                                      }),
            'region':
            autocomplete.ModelSelect2(url='users:region-autocomplete',
                                      forward=['country'],
                                      attrs={
                                          'data-placeholder':
                                          u'Start typing to select a region.',
                                          'data-minimum-input-length': 3
                                      }),
            'city':
            autocomplete.ModelSelect2(url='users:city-autocomplete',
                                      forward=['country', 'region'],
                                      attrs={
                                          'data-placeholder':
                                          u'Start typing to select a city.',
                                          'data-minimum-input-length': 3
                                      })
        }
예제 #19
0
class TablePlotForm(forms.Form):

    plot_types = ['bar', 'heatmap', 'area', 'box', 'violin']
    plot_type = autocomplete.Select2ListChoiceField(
        required=True,
        choice_list=plot_types,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "Select a plot type",
                'data-html': True
            }))
    count_matrix = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Count Matrix",
        widget=autocomplete.ModelSelect2(url='result-countmatrix-autocomplete',
                                         forward=("taxonomy_result", ),
                                         attrs={
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             'data-html': True,
                                             'data-allow-clear': 'true'
                                         }))
    taxonomy_result = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Taxonomic Classification Set",
        widget=autocomplete.ModelSelect2(url='result-taxonomy-autocomplete',
                                         forward=("count_matrix", ),
                                         attrs={
                                             "style":
                                             "flex-grow: 1; width: 50%",
                                             'data-html': True,
                                             'data-allow-clear': 'true'
                                         }))

    normalize_methods = ["raw", "counts", "none", "proportion", "percent"]
    normalize_method = autocomplete.Select2ListChoiceField(
        choice_list=normalize_methods,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "proportion",
                'data-html': True
            }))

    tax_ranks = [
        "Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species",
        "Full"
    ]
    taxonomic_level = autocomplete.Select2ListChoiceField(
        choice_list=tax_ranks,
        widget=autocomplete.ListSelect2(
            attrs={
                "style": "flex-grow: 1",
                "data-placeholder": "Genus",
                'data-html': True
            }))
    plot_height = forms.IntegerField(initial=750)
    metadata_collapse = forms.ModelChoiceField(
        queryset=DataSignature.objects.all(),
        label="Metadata for Aggregation",
        required=False,
        widget=autocomplete.ModelSelect2(
            url='sample-metadata-autocomplete',
            forward=("count_matrix", ),
            attrs={
                "data-allow-clear": "true",
                "data-placeholder": "Select metadata to collapse Samples on",
                "style": "flex-grow: 1; width: 50%",
                "data-html": True
            }))
    metadata_sort = OrderedModelMultipleChoiceField(
        queryset=DataSignature.objects.all(),
        label="Metadata for Sort",
        required=False,
        widget=autocomplete.ModelSelect2Multiple(
            url='sample-metadata-autocomplete',
            forward=("count_matrix", ),
            attrs={
                "data-allow-clear": "true",
                "style": "flex-grow: 1; width: 50%",
                "data-html": True
            }))

    plot_height = forms.IntegerField(initial=750, label="Height (px)")
    n_taxa = forms.IntegerField(initial=25, label="Plot N Most Abundant Taxa")
    label_bars = forms.BooleanField(
        required=False,
        initial=True,
        label="Taxonomic Labels on Bars",
        widget=forms.CheckboxInput(attrs={"class": "big-checkbox"}))
예제 #20
0
class TaxBarSelectForm(forms.Form):
    taxonomy_result = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Taxonomic Classification Set",
        widget=autocomplete.ModelSelect2(url='result-taxonomy-autocomplete',
                                         attrs={
                                             "style": "flex-grow: 1;",
                                             'data-html': True
                                         }))
    count_matrix = forms.ModelChoiceField(
        queryset=Result.objects.all(),
        label="Count Matrix",
        widget=autocomplete.ModelSelect2(url='result-countmatrix-autocomplete',
                                         forward=("taxonomy_result", ),
                                         attrs={
                                             "style": "flex-grow: 1",
                                             'data-html': True
                                         }))
    samples_from_investigation = forms.ModelChoiceField(
        queryset=Investigation.objects.all(),
        required=False,
        label="Select Samples from Investigation",
        widget=autocomplete.ModelSelect2(
            url='object-investigation-autocomplete',
            attrs={
                "data-allow-clear": "true",
                "style": "flex-grow: 1",
                "data-html": True
            }))
    samples = forms.ModelMultipleChoiceField(
        queryset=Sample.objects.all(),
        required=False,
        label="Samples",
        widget=autocomplete.ModelSelect2Multiple(
            url='object-sample-autocomplete',
            forward=('count_matrix', ),
            attrs={
                "data-allow-clear": "true",
                "style": "flex-grow: 1",
                'data-html': True
            }))
    taxonomic_level = autocomplete.Select2ListChoiceField(
        widget=autocomplete.ListSelect2(url='taxonomic-level-autocomplete',
                                        attrs={
                                            "style": "flex-grow: 1",
                                            "data-placeholder": "Genus",
                                            'data-html': True
                                        }))
    plot_height = forms.IntegerField(initial=750)
    #    def __init__(self, *args, **kwargs):
    #        super().__init__(*args, **kwargs)
    #        self.fields['plot_height'].widget.attrs.update({'placeholder': 750,'default':750})
    metadata_sort_by = OrderedModelMultipleChoiceField(
        queryset=DataSignature.objects.all(),
        label="Metadata for Sort",
        required=False,
        widget=autocomplete.ModelSelect2Multiple(
            url='data-signature-autocomplete',
            attrs={
                "data-allow-clear": "true",
                "style": "flex-grow: 1",
                "data-html": True
            }))
    plot_height = forms.IntegerField(initial=750, label="Height (px)")
    n_taxa = forms.IntegerField(initial=25, label="Plot N Most Abundant Taxa")
    label_bars = forms.BooleanField(
        initial=True,
        label="Taxonomic Labels on Bars",
        widget=forms.CheckboxInput(attrs={"class": "big-checkbox"}))