class RequestForAdv(models.Model): """ Class for request for an advertisement from a publisher. """ adsp = models.ManyToManyField(Adspace) name = models.CharField(max_length=NAME_LENGTH) currency = models.CharField(max_length=4, choices=(("eqc", "EQC"), ("xqc", "XQC"))) ask_date_from = models.DateField() ask_date_to = models.DateField() cpi = models.DecimalField(default=0, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) cpm = models.DecimalField(default=0, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) msg = models.CharField(max_length=SHORT_TXT_LENGTH) def __str__(self): return self.name def clean(self): if self.ask_date_from >= self.ask_date_to: raise ValidationError(_('From date should preceed to date.'))
class EventRequest(models.Model): # Example of an event request: "I want to attend yoga class any weekday 5-8pm # at a cost (including travel cost) of no more than $8" # each event request is created by a person person_requesting = models.ForeignKey('Person',related_name='events_requested', on_delete=models.CASCADE,null=True) # event types are manually defined, there are only a few of them # yoga, rockclimbing, tango, freediving event_type = models.CharField('type of event',default='Yoga',blank=False,max_length=200, choices=tuple([(y,y) for y in EVENT_TYPES])) # maximum cost (including travel cost) of the class max_cost = models.DecimalField('maximum cost of the event (including travelling)', default=0,max_digits=6,decimal_places=0, validators=[MinValueValidator(0),DecimalValidator(6,0)]) # travel options travel_types = models.CharField('travel options',default='Rideshare',max_length=200, choices=tuple([(y,y) for y in TRAVEL_TYPES])) # cost of time, per minute travel_time_cost = models.DecimalField('cost of time spent travelling (in mins)', default=0,max_digits=5,decimal_places=2, validators=[MinValueValidator(0),DecimalValidator(5,2)]) def __str__(self): return self.event_type
class Event(models.Model): # Example of an event: "Yoga class with Mary (charging $45) in UNSW gym yoga # room 2 (charging $20), for up to 20 people, on Fri Jan 12th 3pm for one hour # Manually set a few different types of events for now. event_type = models.CharField('type of event',default='Yoga',max_length=200, choices=tuple([(y,y) for y in EVENT_TYPES])) # Events have a many-to-many relationship with Attendees. A person can attend # many events, and an event can have many people attending. attendees = models.ManyToManyField(Person,related_name='events_attending') # Events have a many-to-one relationship with Organizers. An organizer can # host many events, but an event can only have one organizer. 'related_name' is # needed because Event also links to Person via the attendees field organizer = models.ForeignKey(Person,related_name='events_organizing', on_delete=models.CASCADE,null=True) organizer_fee = models.DecimalField(default=0,max_digits=6,decimal_places=0, validators=[MinValueValidator(0),DecimalValidator(6,0)]) # Events have a many-to-one relationship with Venues. A venue can host many # events, but an event can only have one venue. venue = models.ForeignKey(Venue,related_name='events_hosting', on_delete=models.CASCADE,null=True) venue_fee = models.DecimalField(default=0,max_digits=6,decimal_places=0, validators=[MinValueValidator(0),DecimalValidator(6,0)]) # capacity min_people = models.PositiveIntegerField(default=1) max_people = models.PositiveIntegerField(default=100) def __str__(self): return self.event_type
class Stat(models.Model): """ Class for impressions of a given contract. """ contract = models.ManyToManyField(Contract) ## When creating stats with code, we can't assign contracts because it is ## a many to ManyToManyField. The way to do this is to define a 'through' ## model and declare instances of that. See the ticket here : ## https://code.djangoproject.com/ticket/21763 stat_date = models.DateField() impressions = models.IntegerField(unique_for_date="stat_date", validators=[MinValueValidator(0)]) clicks = models.IntegerField(unique_for_date="stat_date", validators=[MinValueValidator(0)]) rpm = models.DecimalField( max_digits=MAX_DIGITS, # unique_for_date=date, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) revenue = models.DecimalField( max_digits=MAX_DIGITS, # unique_for_date=date, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) def __str__(self): return "Stats for date" + str(self.stat_date)
class AdListing(models.Model): """ Class for storing an ad listing from an advertiser """ ad = models.ForeignKey(Ad, on_delete=models.CASCADE) name = models.CharField(max_length=NAME_LENGTH) currency = models.CharField(max_length=4, choices=(("eqc", "EQC"), ("xqc", "XQC"))) ask_date_from = models.DateField() ask_date_to = models.DateField() cpi = models.DecimalField(default=0, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) cpm = models.DecimalField(default=0, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator(MAX_DIGITS, DECIMAL_PLACES) ]) msg = models.CharField(max_length=SHORT_TXT_LENGTH) def __str__(self): return self.name def clean(self): if self.ask_date_from >= self.ask_date_to: raise ValidationError(_('From date should preceed to date.'))
class Location(models.Model): # -90.00000 < latitude < 90.000 latitude = models.DecimalField(max_digits=8,decimal_places=6, validators=[MaxValueValidator(90),MinValueValidator(-90), DecimalValidator(7,5),]) # -180.00000 < longitude < 180.00000 longitude = models.DecimalField(max_digits=9,decimal_places=6, validators=[MaxValueValidator(180),MinValueValidator(-180), DecimalValidator(8,5),])
class ServiceForm(forms.Form): client_id = forms.CharField(max_length=25) location_id = forms.CharField(max_length=50, validators=[validate_slug]) service_type = forms.CharField(max_length=50, validators=[validate_slug]) id = forms.CharField(max_length=50 , validators=[validate_slug]) bandwidth = forms.DecimalField(validators=[DecimalValidator(5,0)]) client_network = forms.CharField(max_length=50, required=False, validators=[validate_ipv46_address]) customer_location_id = forms.DecimalField(validators=[DecimalValidator(10,0)]) prefix = forms.DecimalField(required=False, validators=[validate_prefix]) access_port_id = forms.DecimalField(required=False, validators=[DecimalValidator(10,0)])
class Investment(models.Model): """ Clase que modela una inversion en la bolsa de valores. asset: activo al cual esta vinculada la inversion. (Int) old_buy: precio de compra del activo al momento de la compra (Decimal) old_sell: precio de venta del activo al momento de la compra (Decimal) amount: cantidad de activo. (Decimal) purchased_on: fecha en la que se registro la operacion. (Date) type: tipo de inversion. Puede ser compra o venta. (String) user: usuario al que esta vinculada la inversion. (Int) visible: determina si una inversion es publica(True) o privada(False) """ asset = models.ForeignKey(Asset, related_name='investments', null=False, blank=False, on_delete=models.CASCADE) old_buy = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, validators=[DecimalValidator(10, 2), MinValueValidator( Decimal('0.01'))]) old_sell = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, validators=[ DecimalValidator(10, 2), MinValueValidator(Decimal('0.01'))]) amount = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, validators=[DecimalValidator(10, 2), MinValueValidator( Decimal('0.01'))]) purchased_on = models.DateTimeField(auto_now_add=True, blank=False, null=False) type = models.CharField(max_length=8, choices=INVESTMENT_TYPE, blank=False, null=False, validators=[ProhibitNullCharactersValidator]) user = models.ForeignKey(CustomUser, related_name='investments', blank=False, null=False, on_delete=models.CASCADE) visible = models.BooleanField(blank=False, null=False) def __str__(self): return self.asset.name
class HouseForm(forms.ModelForm): transaction_date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'}), label = 'Transaction Date', help_text = 'Date on which the house would be sold') age = forms.DecimalField(decimal_places=1, label = 'Age', help_text = 'Age of Your House (In years)', validators = [DecimalValidator(decimal_places = 1, max_digits = 10)]) mrt_station = forms.DecimalField(decimal_places=5, label = 'MRT Distance', help_text = 'Distance to nearest MRT Station (In meters)', validators = [DecimalValidator(decimal_places = 5, max_digits = 10)]) convenience_stores = forms.IntegerField(label = 'Convenience Stores', help_text = 'The number of Convenience Stores in proximity to the house (as an Integer)', validators = [validate_int]) latitude = forms.DecimalField(decimal_places=5, label = 'Latitude', help_text = 'Please Use Google Maps to find Latitude', validators = [DecimalValidator(decimal_places = 5, max_digits = 10)]) longitude = forms.DecimalField(decimal_places=5, label = 'Longitude', help_text = 'Please Use Google Maps to find Longitude', validators = [DecimalValidator(decimal_places = 5, max_digits = 10)]) class Meta: model = House fields = ('transaction_date', )
class Currency(models.Model): currency_name = models.CharField('Валюта', max_length=32, blank=True, null=True, default=None) currency_value = models.DecimalField( 'Курс к рублю', max_digits=5, decimal_places=2, default=0, validators=[ MinValueValidator(0, "Введите положительное число"), DecimalValidator(5, 2) ]) is_active = models.BooleanField('Активен', default=True) created = models.DateTimeField('Создан', auto_now_add=True, auto_now=False) updated = models.DateTimeField('Последнее обновление', auto_now_add=False, auto_now=True) def __str__(self): return "%s" % self.currency_name class Meta: verbose_name = 'Валюта' verbose_name_plural = 'Валюты'
class ExampleValidatedSerializer(serializers.Serializer): integer = serializers.IntegerField(validators=( MaxValueValidator(limit_value=99), MinValueValidator(limit_value=-11), )) string = serializers.CharField(validators=( MaxLengthValidator(limit_value=10), MinLengthValidator(limit_value=2), )) regex = serializers.CharField( validators=(RegexValidator(regex=r'[ABC]12{3}'), ), help_text='must have an A, B, or C followed by 1222') lst = serializers.ListField(validators=( MaxLengthValidator(limit_value=10), MinLengthValidator(limit_value=2), )) decimal1 = serializers.DecimalField(max_digits=6, decimal_places=2) decimal2 = serializers.DecimalField( max_digits=5, decimal_places=0, validators=(DecimalValidator(max_digits=17, decimal_places=4), )) email = serializers.EmailField(default='*****@*****.**') url = serializers.URLField(default='http://www.example.com', allow_null=True) uuid = serializers.UUIDField() ip4 = serializers.IPAddressField(protocol='ipv4') ip6 = serializers.IPAddressField(protocol='ipv6') ip = serializers.IPAddressField()
class Product(models.Model): NONE = 'NON' SQUARE_METER = 'м²' RUNNING_METER = 'м. пог.' UNIT = 'Шт.' PACKING = 'Уп.' PRODUCT_UNIT = ( (NONE, 'Не указано'), (SQUARE_METER, 'м²'), (RUNNING_METER, 'м. пог.'), (UNIT, 'шт.'), (PACKING, 'упак.'), ) product_name = models.CharField('Название', max_length=64) product_article = models.CharField('Артикл', max_length=32) product_price = models.DecimalField('Цена', max_digits=10, decimal_places=2, default=0, validators=[ MinValueValidator( 0, "Введите положительное число"), DecimalValidator(10, 2) ]) product_currency = models.ForeignKey(Currency, blank=True, null=True, default=None) product_unit = models.CharField('Единица измерения', max_length=10, choices=PRODUCT_UNIT, default=NONE) product_store = models.ForeignKey(Store, related_name='product_store', blank=True, null=True, default=None) product_manufacturer = models.ForeignKey( Manufacturer, related_name='product_manufacturer') product_category = models.ForeignKey(Category) product_provider = models.ForeignKey(Provider, related_name='product_provider', blank=True, null=True, default=None) is_active = models.BooleanField(IS_ACTIVE, default=True) created = models.DateTimeField(CREATED, auto_now_add=True, auto_now=False) updated = models.DateTimeField(UPDATED, auto_now_add=False, auto_now=True) def __str__(self): return "%s %s" % (self.product_name, self.product_article) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' ordering = ["product_manufacturer"]
class Product(models.Model): id = models.IntegerField(serialize=True, primary_key=True) name = models.CharField(max_length=150, null=False) description = models.CharField(max_length=300, null=False) base_price = models.FloatField(null=False, validators=[DecimalValidator(18, 4)]) in_offer = models.BooleanField(default=False) image = models.TextField(null=False) state = models.ForeignKey(State, null=False, on_delete=models.DO_NOTHING)
def clean(self): super(JobParameter, self).clean() if PARAMETER_TYPE_CHOICES[self.type][1] == "Integer": try: DecimalValidator(max_digits=None, decimal_places=0)(Decimal(self.value)) except (ValidationError, InvalidOperation): raise ValidationError({ 'value': ValidationError('Invalid integer value: "%(value)s"', code='invalid', params={'value': self.value}) }) if PARAMETER_TYPE_CHOICES[self.type][1] == "Decimal": try: DecimalValidator(max_digits=None, decimal_places=None)(Decimal(self.value)) except (ValidationError, InvalidOperation): raise ValidationError({ 'value': ValidationError('Invalid decimal value: "%(value)s"', code='invalid', params={'value': self.value}) }) if PARAMETER_TYPE_CHOICES[self.type][1] == "Boolean": if self.value.lower() not in ["true", "false"]: raise ValidationError({ 'value': ValidationError('Invalid boolean value: "%(value)s"', code='invalid', params={'value': self.value}) }) if PARAMETER_TYPE_CHOICES[self.type][1] == "Datetime": try: self.value = parse(self.value).isoformat() except ValueError: raise ValidationError({ 'value': ValidationError('Invalid datetime value: "%(value)s"', code='invalid', params={'value': self.value}) })
class Agent(models.Model): """ Class for agent. An agent is both publisher and advertiser. """ user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True) bio = models.CharField(max_length=SHORT_TXT_LENGTH, null=True) e_balance = models.DecimalField( default=Decimal('0.00000000'), max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[DecimalValidator(MAX_DIGITS, DECIMAL_PLACES)]) x_balance = models.DecimalField( default=Decimal('0.00000000'), max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[DecimalValidator(MAX_DIGITS, DECIMAL_PLACES)]) def __str__(self): return self.user.username
def validate_decimal(value): ''' Raises ``ValidationError`` unless *value* can be cast as a ``Decimal`` ''' try: assert type(value) in (str, float, int, Decimal) casted = Decimal(value) decimal_validator = DecimalValidator(10, 2) decimal_validator(casted) return casted except (ValueError, AssertionError): raise ValidationError(_(u"Must be a float or valid string"))
class Movie(models.Model): """ Model for Movie fields : name - varchar imdb_score - Decimal 0 to 10 director - varchar popularity - Decimal 0 to 99 genre - List of Genre Object - Many to Many field """ name = models.CharField(max_length=200) imdb_score = models.DecimalField(max_digits=3, decimal_places=1, validators=[MaxValueValidator(10), DecimalValidator(3, 1), MinValueValidator(Decimal('0.0'))]) director = models.CharField(max_length=200) popularity = models.DecimalField(max_digits=3, decimal_places=1, validators=[MaxValueValidator(99), DecimalValidator(3, 1), MinValueValidator(Decimal('0.0'))]) genre = models.ManyToManyField(Genre) def __str__(self): return self.name
class Venue(models.Model): # Example of a venue: "UNSW Gym Yoga room 2, capacity 25 people, available # for rent by the general public Mon and Wed afternoons 2-5pm for $30ph" name = models.CharField(max_length=200,default='') location = models.OneToOneField(Location,on_delete=models.CASCADE,null=True) capacity = models.PositiveIntegerField(default=0) cost_per_hour = models.DecimalField(max_digits=7,decimal_places=5, validators=[MinValueValidator(0),DecimalValidator(7,5)]) def __str__(self): return self.name
class AdListing(models.Model): """ Class for storing an ad listing from an advertiser """ ad = models.ForeignKey(Ad, on_delete=models.CASCADE) name = models.CharField(max_length=NAME_LENGTH) currency = models.CharField(max_length=4, choices=(("eqc", "EQC"), ("xqc", "XQC"))) asking_rate = models.DecimalField(max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, validators=[ MinValueValidator(0), DecimalValidator( MAX_DIGITS, DECIMAL_PLACES) ]) ask_date_from = models.DateField() ask_date_to = models.DateField() msg = models.CharField(max_length=SHORT_TXT_LENGTH)
class Delivery(models.Model): NONE = 'В обработке' CONFIRMED = 'Подтверждён' FORMED = 'Сформирован' DELIVERED = 'Доставляется' RECEIVED = 'Доставлено' CANCEL = 'Отмена' DELIVERY_STATUSES = ( (NONE, 'В обработке'), (CONFIRMED, 'Доставка подтверждена'), (FORMED, 'Груз сформирован'), (DELIVERED, 'В пути'), (RECEIVED, 'Доставлено'), (CANCEL, 'Доставка отменена'), ) delivery_order = models.ForeignKey('Order', related_name='delivery_order') delivery_type = models.ForeignKey(DeliveryType) delivery_address = models.ForeignKey(Address) delivery_date = models.DateField('Дата доставки', blank=False) delivery_price = models.DecimalField( 'Стоимость доставки', max_digits=10, decimal_places=2, default=0, validators=[ MinValueValidator(0, "Введите положительное число"), DecimalValidator(10, 2) ]) delivery_status = models.CharField('Статус доставки', max_length=12, choices=DELIVERY_STATUSES, default=NONE) is_active = models.BooleanField(IS_ACTIVE, default=True) created = models.DateTimeField(CREATED, auto_now_add=True, auto_now=False) updated = models.DateTimeField(UPDATED, auto_now_add=False, auto_now=True) def __str__(self): return "Доставка №%s заказ №%s" % (self.id, self.delivery_order_id) class Meta: verbose_name = 'Доставка' verbose_name_plural = 'Доставки' ordering = ["-updated"]
def test_decimal_equality(self): self.assertEqual( DecimalValidator(1, 2), DecimalValidator(1, 2), ) self.assertNotEqual( DecimalValidator(1, 2), DecimalValidator(1, 1), ) self.assertNotEqual( DecimalValidator(1, 2), DecimalValidator(2, 2), ) self.assertNotEqual( DecimalValidator(1, 2), MinValueValidator(11), )
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["descripcion"].required = False self.fields["emergencia"].required = False self.fields["nombre"].validators.insert( 0, RegexValidator( TipoDeAtencion.REGEX_NOMBRE, message= "El nombre puede tener numeros, letras, espacios, guiones y puntos." )) self.fields["recargo"].validators.extend([ MaxValueValidator(TipoDeAtencion.RECARGO_MAX_VALUE), MinValueValidator(TipoDeAtencion.RECARGO_MIN_VALUE), DecimalValidator( TipoDeAtencion.RECARGO_PARTE_ENTERA + TipoDeAtencion.RECARGO_PARTE_DECIMAL, TipoDeAtencion.RECARGO_PARTE_DECIMAL) ]) self.fields["inicioFranjaHoraria"].input_formats = TIME_INPUT_FMTS self.fields["finFranjaHoraria"].input_formats = TIME_INPUT_FMTS self.fields["inicioFranjaHoraria"].widget.format = TIME_INPUT_FMTS[0] self.fields["finFranjaHoraria"].widget.format = TIME_INPUT_FMTS[0] self.fields["tipoDeServicio"].choices = Areas.paresOrdenados() self.fields["lugar"].choices = TipoDeAtencion.LUGARES_DE_ATENCION self.fields["nombre"].widget.attrs.update({"class": "form-control"}) self.fields["descripcion"].widget.attrs.update({ "class": "form-control", "cols": 60, "rows": 4 }) self.fields["tipoDeServicio"].widget.attrs.update( {"class": "form-control"}) self.fields["lugar"].widget.attrs.update({"class": "form-control"}) self.fields["inicioFranjaHoraria"].widget.attrs.update( {"class": "form-control"}) self.fields["finFranjaHoraria"].widget.attrs.update( {"class": "form-control"}) self.fields["recargo"].widget.attrs.update({"class": "form-control"})
def form_valid(self, form): account = get_object_or_404(Account, pk=self.kwargs.get('pk'), user=self.request.user) account.balance += form.instance.amount decimal_validator = DecimalValidator(DECIMAL_MAX, 2) try: decimal_validator(account.balance) except ValidationError: form.add_error('amount', 'Invalid amount. Account balance out of bounds.') return self.form_invalid(form) account.last_transaction_number += 1 form.instance.balance = account.balance form.instance.transaction_number = account.last_transaction_number form.instance.account = account form.save() account.save() return super(FormView, self).form_valid(form)
class Payment(models.Model): WAITING_FOR_PAYMENT = 'Ожидание' CONFIRMED = 'Подтверждена' CANCEL = 'Отмена' PAID_STATUSES = ( (WAITING_FOR_PAYMENT, 'Ожидание оплаты'), (CONFIRMED, 'Оплата подтверждена'), (CANCEL, 'Оплата отменена'), ) payment_order = models.ForeignKey('Order', related_name='payment_order') payment_type = models.ForeignKey(PaymentType) payment_amount = models.DecimalField( 'Размер платежа', max_digits=10, decimal_places=2, default=0, validators=[ MinValueValidator(0, "Введите положительное число"), DecimalValidator(10, 2) ]) payment_status = models.CharField('Статус платежа', max_length=12, choices=PAID_STATUSES, default=WAITING_FOR_PAYMENT) is_active = models.BooleanField('Активен', default=True) created = models.DateTimeField('Создан', auto_now_add=True, auto_now=False) updated = models.DateTimeField('Последнее обновление', auto_now_add=False, auto_now=True) def __str__(self): return "Платёж №%s заказ №%s" % (self.id, self.payment_order_id) class Meta: verbose_name = 'Платёж' verbose_name_plural = 'Платежи' ordering = ["-created"]
class Bid(models.Model): class Meta: get_latest_by = 'last_modified' ordering = ['amount'] auction = models.ForeignKey( 'Auction', on_delete=models.CASCADE, help_text="Auction the bid was made on" ) bidder = models.ForeignKey( User, on_delete=models.CASCADE, help_text="User who placed the bid" ) amount = models.DecimalField( decimal_places=2, max_digits=20, help_text="Amount bid", validators=[ DecimalValidator(max_digits=20, decimal_places=2), MinValueValidator(0.01), ] ) created = models.DateTimeField( auto_now_add=True, #set to now upon creation editable=False, help_text="When bid was placed" ) last_modified = models.DateTimeField( auto_now=True, #sets date every time the object is saved editable=False, help_text="When bid was last updated" )
class InvoiceItem(models.Model): TAX_STATUS = (('STANDARD', 'Standard rate'), ('REDUCED', 'Reduced rate'), ('ZERO', 'Zero rated')) # To change, create new item and 'retire' old one # (thus not effective existing invoices & preserving item history in the DB). datetime_created = models.DateTimeField(default=timezone.now, blank=False, null=True, verbose_name='Created') item_name = models.CharField(max_length=255, blank=False, null=True, verbose_name='Item') desc = models.CharField(max_length=255, blank=False, null=True, verbose_name='Description') price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'), blank=False, null=True, verbose_name='Price', validators=[DecimalValidator(6, 2)]) tax_status = models.CharField(max_length=11, blank=False, null=False, default=TAX_STATUS[0][0], choices=TAX_STATUS, verbose_name='Tax status') retired = models.BooleanField(blank=False, null=False, default=False, verbose_name='Deactivate') def __str__(self): return self.item_name
class Post(models.Model): date_of_birth = models.DateField(_("date of birth"), null=True, validators=[validate_date_of_birth]) file = models.FileField( _("file"), upload_to='file/', max_length=100, null=True, validators=[ validate_image_file_extension, # FileExtensionValidator( # allowed_extensions=['xlsx', 'jpg'], # message='Не тот файл!' # ) ]) number = models.DecimalField( _("number"), max_digits=9, decimal_places=3, null=True, validators=[DecimalValidator(max_digits=5, decimal_places=2)]) interval_length = models.CharField(_("interval length"), max_length=50, null=True, validators=[ MinLengthValidator(limit_value=9, message='9'), MaxLengthValidator(limit_value=42, message='42') ]) interval_value = models.IntegerField( _("interval"), null=True, validators=[ MaxValueValidator(limit_value=42, message='Не более 42'), MinValueValidator(limit_value=9, message='Не менее 9') ]) int_list_sep = models.CharField(_("list sep"), max_length=50, null=True, validators=[ int_list_validator( sep=':', allow_negative=True, message='Используйте двоетечие!') ]) int_list_comma = models.CharField( _("list comma"), max_length=50, null=True, validators=[validate_comma_separated_integer_list]) # ip = models.GenericIPAddressField(_("ip"), protocol="both", unpack_ipv4=False) ip = models.CharField( _("ip"), max_length=50, null=True, validators=[ # validate_ipv4_address, # validate_ipv6_address, validate_ipv46_address ]) # url = models.SlugField(_("url"), allow_unicode=True) # validate_slug | validate_unicode_slug # url = models.URLField(_("url"), max_length=200) # URLValidator url = models.CharField( _("url"), max_length=50, null=True, validators=[ # validate_slug, # validate_unicode_slug, URLValidator(message='Введите корректный URL', schemes=['https']) ]) # email = models.EmailField(_("email"), max_length=254) validate_email email = models.CharField( _("email"), max_length=50, null=True, validators=[ # validate_email, EmailValidator(message='Введите корректный email', whitelist=['localhost', 'my_local']) ]) title = models.CharField( _("title"), max_length=50, validators=[ RegexValidator( regex=r'\.$', # regex=re.compile() message='Поставьте точку в конце!', code='invalid', # required inverse_match=True, flags=re.IGNORECASE # https://docs.python.org/3/library/re.html#contents-of-module-re ) ]) name = models.CharField(_("name"), max_length=150) slug = models.SlugField(_("url")) class Meta: verbose_name = _("post") verbose_name_plural = _("posts") db_table = 'posts' def __str__(self): return self.name def get_absolute_url(self): return reverse("post_detail", kwargs={"slug": self.slug})
(FileExtensionValidator(['txt']), ContentFile('contents', name='fileWithNoExtension'), ValidationError), (FileExtensionValidator(['']), ContentFile('contents', name='fileWithAnExtension.txt'), ValidationError), (FileExtensionValidator([]), ContentFile('contents', name='file.txt'), ValidationError), (FileExtensionValidator(['']), ContentFile('contents', name='fileWithNoExtension'), None), (FileExtensionValidator(['txt']), ContentFile('contents', name='file.txt'), None), (FileExtensionValidator(['txt']), ContentFile('contents', name='file.TXT'), None), (FileExtensionValidator(['TXT']), ContentFile('contents', name='file.txt'), None), (FileExtensionValidator(), ContentFile('contents', name='file.jpg'), None), (DecimalValidator(max_digits=2, decimal_places=2), Decimal('0.99'), None), (DecimalValidator(max_digits=2, decimal_places=1), Decimal('0.99'), ValidationError), (DecimalValidator(max_digits=3, decimal_places=1), Decimal('999'), ValidationError), (DecimalValidator(max_digits=4, decimal_places=1), Decimal('999'), None), (DecimalValidator(max_digits=20, decimal_places=2), Decimal('742403889818000000'), None), (DecimalValidator(20, 2), Decimal('7.42403889818E+17'), None), (DecimalValidator(max_digits=20, decimal_places=2), Decimal('7424742403889818000000'), ValidationError), (DecimalValidator(max_digits=5, decimal_places=2), Decimal('7304E-1'), None), (DecimalValidator(max_digits=5, decimal_places=2), Decimal('7304E-3'), ValidationError), (DecimalValidator(max_digits=5, decimal_places=5), Decimal('70E-5'), None),
from datetime import date from django import forms from django.core.validators import DecimalValidator, MinValueValidator from .models import * from helpers import remove_html_tags from input.queries import get_subtypes_for_choicefield decimalValidators = [ MinValueValidator(limit_value=0.0), DecimalValidator(max_digits=10, decimal_places=2) ] class DonorInformationForm(forms.ModelForm): first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) email = forms.EmailField(required=False) phone_number = forms.CharField(required=False) address1 = forms.CharField(required=False) address2 = forms.CharField(required=False) city = forms.CharField(required=False) state = forms.CharField(required=False) zip = forms.CharField(required=False) class Meta: model = Donor fields = [ 'first_name', 'last_name', 'phone_number', 'address1', 'address2', 'city', 'state', 'zip', 'email' ]
class TipoDeAtencion(models.Model): objects = TipoDeAtencionManager() RECARGO_PARTE_ENTERA = 3 RECARGO_PARTE_DECIMAL = 2 RECARGO_MIN_VALUE = Decimal(0) RECARGO_MAX_VALUE = Decimal(900.00) MAX_NOMBRE = 100 MIN_NOMBRE = 1 REGEX_NOMBRE = "^[0-9áéíóúÁÉÍÓÚñÑa-zA-Z-_ .]{%d,%d}$" % (MIN_NOMBRE, MAX_NOMBRE) EN_VETERINARIA = "V" EN_DOMICILIO = "D" LUGARES_DE_ATENCION = ( (EN_VETERINARIA, "Veterinaria"), (EN_DOMICILIO, "Domicilio") ) RECARGO_DEFAULT = Decimal(0) LUGAR_DEFAULT = EN_VETERINARIA id = models.AutoField( primary_key=True, unique=True, editable=False ) nombre = models.CharField( max_length=MAX_NOMBRE, unique=True, validators = [ RegexValidator(regex=REGEX_NOMBRE) ], error_messages = { "unique" : "Otro tipo de atencion tiene ese nombre", "max_length" : "El nombre puede tener a lo sumo {} caracteres".format(MAX_NOMBRE), "blank" : "El nombre es obligatorio" } ) descripcion = models.TextField( blank=True, ) emergencia = models.BooleanField( default=False ) lugar = models.CharField( max_length=1, default=LUGAR_DEFAULT, choices=LUGARES_DE_ATENCION, error_messages = { "invalid_choice" : "La opcion no es valida", "blank" : "El lugar de atencion es obligatorio" } ) recargo = models.DecimalField( max_digits=RECARGO_PARTE_ENTERA+RECARGO_PARTE_DECIMAL, decimal_places=RECARGO_PARTE_DECIMAL, default=RECARGO_DEFAULT, validators = [ MinValueValidator(RECARGO_MIN_VALUE, message=("El recargo no puede ser menor a {:.%df}" % (RECARGO_PARTE_DECIMAL)).format(RECARGO_MIN_VALUE)), MaxValueValidator(RECARGO_MAX_VALUE, message=("El recargo no puede ser mayor a {:.%df}" % (RECARGO_PARTE_DECIMAL)).format(RECARGO_MAX_VALUE)), DecimalValidator(max_digits=RECARGO_PARTE_ENTERA+RECARGO_PARTE_DECIMAL, decimal_places=RECARGO_PARTE_DECIMAL) ] ) tipoDeServicio = models.CharField( max_length=Areas.caracteresCodigo(), choices=Areas.choices(), error_messages = { "invalid_choice" : "La opcion no es valida", "blank" : "El tipo de servicio es obligatorio" } ) inicioFranjaHoraria = models.TimeField( error_messages = { "invalid" : "El formato debe ser <horas>:<minutos>, por ejemplo 01:23", "blank" : "El inicio de horario de atencion es obligatorio" } ) finFranjaHoraria = models.TimeField( error_messages = { "invalid" : "El formato debe ser <horas>:<minutos>, por ejemplo 01:23", "blank" : "El inicio de horario de atencion es obligatorio" } ) baja = models.BooleanField( default=False, editable=False ) def __str__(self): """ String para Tipos de Atencion """ return self.nombre @property def franjaHoraria(self): """ FranjaHoraria a partir de inicio y fin """ return FranjaHoraria(self.inicioFranjaHoraria, self.finFranjaHoraria) @franjaHoraria.setter def franjaHoraria(self, franja): """ Inicio y fin desde FranjaHoraria """ self.inicioFranjaHoraria = franja.inicio self.finFranjaHoraria = franja.fin