@classmethod def by_documento(cls, tipo_documento, numero_documento, cpf_cnpj_fornecedor, associacao__uuid): return cls.objects.filter(associacao__uuid=associacao__uuid).filter( cpf_cnpj_fornecedor=cpf_cnpj_fornecedor).filter( tipo_documento=tipo_documento).filter( numero_documento=numero_documento).first() class Meta: verbose_name = "Despesa" verbose_name_plural = "Despesas" @receiver(pre_save, sender=Despesa) def proponente_pre_save(instance, **kwargs): instance.status = STATUS_COMPLETO if instance.cadastro_completo( ) else STATUS_INCOMPLETO @receiver(post_save, sender=Despesa) def rateio_post_save(instance, created, **kwargs): # Existe um motivo para o fornecedor não ser uma FK nesse modelo e ele ser atualizado indiretamente # A existência da tabela de fornecedores é apenas para facilitar o preenchimento da despesa pelas associações # Alterações feitas por uma associação no nome de um fornecedor não deve alterar diretamente as despesas de outras if instance and instance.cpf_cnpj_fornecedor and instance.nome_fornecedor: Fornecedor.atualiza_ou_cria(cpf_cnpj=instance.cpf_cnpj_fornecedor, nome=instance.nome_fornecedor) auditlog.register(Despesa)
name = models.CharField(_('Name'),max_length=120) description = models.TextField(_('Description'), blank=True) project = models.ForeignKey(Project, verbose_name=_('Project'), related_name='milestones') date = models.DateField(_('Date')) milestone_type = models.CharField(max_length=5, verbose_name=_('Milestone type'), choices=MILESTONE_TYPES, default=MILESTONE_OTHER) history = AuditlogHistoryField() def __str__(self): return self.name class Meta: ordering = ('date',) class ProjectMembership(TimeStampedModel): MEMBER_ROLE = 'MEMBER' LEADER_ROLE = 'LEADER' ROLES = ((MEMBER_ROLE, _('Member')), (LEADER_ROLE, _('Leader'))) member = models.ForeignKey(Employee, related_name='projects', verbose_name=_('Member')) project = models.ForeignKey(Project, related_name='members', verbose_name=_('Project')) role = models.CharField(max_length=6, choices=ROLES, default=MEMBER_ROLE) auditlog.register(Project) auditlog.register(Assumption, exclude_fields=['display_order']) auditlog.register(Restriction, exclude_fields=['display_order']) auditlog.register(Milestone)
from auditlog.models import AuditlogHistoryField from django.db import models from django.contrib.auth import get_user_model from django.contrib.postgres.fields import JSONField from api.users.models import CustomUser class Favorite(models.Model): CATEGORY_CHOICES = [('pe', 'person'), ('pl', 'place'), ('fo', 'food')] customuser = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255, null=False, blank=False) description = models.CharField(max_length=300, null=False) ranking = models.IntegerField(null=False, blank=False) metadata = JSONField(null=True) category = models.CharField(max_length=255, choices=CATEGORY_CHOICES, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) history = AuditlogHistoryField() def __str__(self): return "{} - {} - {}".format(self.title, self.ranking, self.category) auditlog.register(Favorite)
def tearDown(self): # Re-register for future tests auditlog.register(SimpleModel)
class Meta: abstract = True class OrderArrivedMessageLog(MessageLog): order_arrived_reminder = models.ForeignKey( OrderArrivedReminder, on_delete=models.SET_NULL, null=True ) class UnpaidClaimMessageLog(MessageLog): unpaid_claim_reminder = models.ForeignKey( UnpaidClaimReminder, on_delete=models.SET_NULL, null=True ) class BenefitsMessageLog(MessageLog): benefits_reminder = models.ForeignKey( BenefitsReminder, on_delete=models.SET_NULL, null=True ) auditlog.register(OrderArrivedReminder) auditlog.register(UnpaidClaimReminder) auditlog.register(BenefitsReminder) auditlog.register(ClaimOrderReminder)
information about the model in JSON """ label = models.CharField(max_length=100) text = models.TextField(blank=True) related = models.ForeignKey(SimpleModel) history = AuditlogHistoryField() def get_additional_data(self): """ Returns JSON that captures a snapshot of additional details of the model instance. This method, if defined, is accessed by auditlog manager and added to each logentry instance on creation. """ object_details = { 'related_model_id': self.related.id, 'related_model_text': self.related.text } return object_details auditlog.register(SimpleModel) auditlog.register(AltPrimaryKeyModel) auditlog.register(ProxyModel) auditlog.register(RelatedModel) auditlog.register(ManyRelatedModel) auditlog.register(ManyRelatedModel.related.through) auditlog.register(SimpleIncludeModel, include_fields=['label']) auditlog.register(SimpleExcludeModel, exclude_fields=['text']) auditlog.register(AdditionalDataIncludedModel)
from django.db import models from auditlog.registry import auditlog # Create your models here. class InfoAbst(models.Model): nome = models.CharField(max_length = 100) telefone = models.CharField(max_length=15, help_text='Seguir o formato como exemplo: 83-11111-2222') email = models.EmailField(max_length = 70) class Meta: abstract = True class Cliente(InfoAbst): cpf = models.PositiveIntegerField(max_length = 11, blank = True, null = True, help_text='Digitar apenas numeros', unique = True) cnpj = models.PositiveIntegerField(max_length = 14, blank = True, null = True, help_text='Digitar apenas numeros', unique = True) endereco = models.ManyToManyField('enderecos.Endereco') num = models.PositiveIntegerField(blank = True, null = True) def __unicode__(self): return self.nome auditlog.register(Cliente)
"""Modelos da aplicação core.""" from auditlog.models import AuditlogHistoryField from auditlog.registry import auditlog from django.contrib.auth.models import AbstractUser from model_utils.models import TimeStampedModel class Usuário(TimeStampedModel, AbstractUser): """Usuário base do projeto.""" histórico = AuditlogHistoryField() class Meta: """Meta opções para o modelo Usuário.""" ordering = ['-id'] auditlog.register(Usuário)
db_table = "road_marking_real_operation" ordering = ["operation_date"] verbose_name = _("Road marking real operation") verbose_name_plural = _("Road marking real operations") class RoadMarkingRealFile(models.Model): id = models.UUIDField(primary_key=True, unique=True, editable=False, default=uuid.uuid4) file = models.FileField(_("File"), blank=False, null=False, upload_to="realfiles/road_marking/") road_marking_real = models.ForeignKey(RoadMarkingReal, on_delete=models.CASCADE, related_name="files") class Meta: db_table = "road_marking_real_file" verbose_name = _("RoadMarking Real File") verbose_name_plural = _("RoadMarking Real Files") def __str__(self): return f"{self.file}" auditlog.register(RoadMarkingPlan) auditlog.register(RoadMarkingReal)
GREEN = 'g' STATUS_CHOICES = ( (RED, 'Red'), (YELLOW, 'Yellow'), (GREEN, 'Green'), ) arrayfield = ArrayField(models.CharField(max_length=1, choices=STATUS_CHOICES), size=3) class NoDeleteHistoryModel(models.Model, AuditLogHistoryMixin): integer = models.IntegerField(blank=True, null=True) auditlog.register(AltPrimaryKeyModel) auditlog.register(UUIDPrimaryKeyModel) auditlog.register(ProxyModel) auditlog.register(RelatedModel) auditlog.register(ManyRelatedModel) auditlog.register(ManyRelatedModel.related.through) auditlog.register(SimpleExcludeModel, exclude_fields=['text']) auditlog.register(SimpleMappingModel, mapping_fields={'sku': 'Product No.'}) auditlog.register(AdditionalDataIncludedModel) auditlog.register(DateTimeFieldModel) auditlog.register(ChoicesFieldModel) auditlog.register(CharfieldTextfieldModel) auditlog.register(PostgresArrayFieldModel) auditlog.register(NoDeleteHistoryModel)
null=True, blank=True, on_delete=models.PROTECT, ) # In Finnish: Päätöspäivämäärä decision_date = models.DateField(verbose_name=_("Decision date"), null=True, blank=True) # In Finnish: Pykälä section = models.CharField(verbose_name=_("Section"), null=True, blank=True, max_length=255) recursive_get_related_skip_relations = ["basis_of_rent"] class Meta: verbose_name = pgettext_lazy("Model name", "Basis of rent decision") verbose_name_plural = pgettext_lazy("Model name", "Basis of rent decisions") auditlog.register(BasisOfRent) field_permissions.register(BasisOfRent) field_permissions.register(BasisOfRentRate, exclude_fields=["basis_of_rent"]) field_permissions.register(BasisOfRentDecision, exclude_fields=["basis_of_rent"])
if extra_data['gender'] == 'male': user.gender = 'M' elif extra_data['gender'] == 'female': user.gender = 'F' if sociallogin.account.provider == 'google': pass # user.first_name = sociallogin.account.extra_data['given_name'] # user.last_name = sociallogin.account.extra_data['family_name'] # verified = sociallogin.account.extra_data['verified_email'] # picture_url = sociallogin.account.extra_data['picture'] user.save() auditlog.register(Membership) auditlog.register(Renewal) auditlog.register(CardStatus) # def get_members_summary(): # from docx import Document # # document = Document() # document.add_page_break() # members = Membership.objects.filter(user__devil_no__isnull=False) # for member in members: # p = document.add_paragraph('') # p.add_run('#' + str(member.user.devil_no)) # p.add_run('\n') # p.add_run(member.user.full_name)
from django.db import models from auditlog.registry import auditlog from geoposition.fields import GeopositionField from localflavor.br.br_states import STATE_CHOICES # Create your models here. class Mapas(models.Model): mapas = models.CharField(max_length=255) # estado = models.CharField(max_length=2, null=True, blank=True)#choices=STATE_CHOICES position = GeopositionField(verbose_name=u'Geolocalizacao') class Meta: verbose_name, verbose_name_plural = u"Sua Classe" , u"GPS" # ordering = ('cidade',) def __unicode__(self): return self.mapas auditlog.register(Mapas)
from auditlog.registry import auditlog from .biomechanics import BiomechanicalFoot, BiomechanicalGait from .claims import Claim, ClaimAttachment, ClaimCoverage, ClaimItem, \ ProofOfManufacturing, Receipt, Invoice from .clients import Person, Client, Dependent, Note from .credit_devisor import CreditDivisor from .insurance_info import Insurance, Coverage from .insurance_letter import InsuranceLetter, Laboratory from .items import Item, ItemHistory from .referrals import Referral auditlog.register(Person) auditlog.register(Client) auditlog.register(Note) auditlog.register(Dependent) auditlog.register(Insurance) auditlog.register(Coverage) auditlog.register(Item) auditlog.register(ItemHistory) auditlog.register(Invoice) auditlog.register(Claim) auditlog.register(ClaimAttachment) auditlog.register(ClaimCoverage) auditlog.register(ClaimItem) auditlog.register(InsuranceLetter) auditlog.register(ProofOfManufacturing) auditlog.register(BiomechanicalGait) auditlog.register(BiomechanicalFoot) auditlog.register(Laboratory)
indexes = [models.Index(fields=["-created"])] def __str__(self): return f"<OfferedBoardOptions created at {self.created}>" class ExternalBoardOptions(models.Model): """Model to store the board options externally available in some PCB shop at any given time.""" created = models.DateTimeField(auto_now_add=True) external_shop = models.ForeignKey(ExternalShop, on_delete=models.DO_NOTHING) attribute_options = models.JSONField() class Meta: ordering = ['-created'] verbose_name = "External Board Options" verbose_name_plural = "External Board Options List" indexes = [models.Index(fields=["-created"])] def __str__(self): return f"<ExternalBoardOptions from shop '{self.external_shop.name}'>" auditlog.register(ArticleCategory) auditlog.register(Article) auditlog.register(Board) auditlog.register(ExternalShop) auditlog.register(OfferedBoardOptions) auditlog.register(ExternalBoardOptions)
def publish(self): """ This function may contain side-effects, like updating caches, notifying users, etc. The return value will be discarded. """ @transition(field=status, source=["new", "published"], target="destroyed") def destroy(self): """ Side effects galore """ @transition(field=status, source="published", target="new") def unpublish(self): """ This function may contain side-effects, like updating caches, notifying users, etc. The return value will be discarded. """ @property def formatted_title(self): if self.title: if len(self.title) > 16: return self.title[0:13] + "..." return self.title auditlog.register(Event)
class Meta: unique_together = ['re_funcionario', 'unidade'] def __str__(self): return f'Funcionário : {self.re_funcionario} ' def save(self, *args, **kwargs): self.nome = self.nome.upper() print(f'{self.id} : {self.nome} Foi salvo com sucesso! \n') super(Funcionario, self).save(*args, **kwargs) auditlog.register(Funcionario, exclude_fields=['user'], mapping_fields={ 'telefone': 'Telefone', 'email': 'E-mail Pessoal' }) def create_user(sender, instance, created, **kwargs): if created: user = User.objects.create_user(username=str(instance.unidade.id) + str(instance.re_funcionario)) user.set_password(instance.re_funcionario) grupo = Group.objects.get(id=3) user.groups.add(grupo) user.save() print(user.username, "Foi salvo com sucesso!") instance.usuario = user instance.save()
from auditlog.registry import auditlog from django.db import models class Case(models.Model): total = models.IntegerField() recovered = models.IntegerField() deaths = models.IntegerField() county = models.ForeignKey("County", on_delete=models.CASCADE) as_of = models.DateField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = [ "-as_of", "county__name", "id", ] unique_together = [["county", "as_of"]] def __str__(self): return f"{self.as_of} {self.county.name}" auditlog.register(Case)
def __unicode__(self): return self.name # meant to be an answered survey tied to an engagement class Answered_Survey(models.Model): # tie this to a specific engagement engagement = models.ForeignKey(Engagement, related_name='engagement', null=True, blank=False, editable=True) # what surveys have been answered survey = models.ForeignKey(Engagement_Survey) # who answered it responder = models.ForeignKey(User, related_name='responder', null=True, blank=True, editable=True, default=None) completed = models.BooleanField(default=False) answered_on = models.DateField(null=True) class Meta: verbose_name = "Answered Engagement Survey" verbose_name_plural = "Answered Engagement Surveys" def __unicode__(self): return self.survey.name auditlog.register(Answer) auditlog.register(Answered_Survey) auditlog.register(Question) auditlog.register(Engagement_Survey)
type = models.CharField(max_length=15) description = models.TextField(blank=True, null=True) passed_tense = models.CharField( max_length=20, help_text='The passed tense of the event word. Example: Bloomed') def __str__(self): return self.type class EventReport(models.Model): event_report_id = models.AutoField(primary_key=True) submitted_by = models.ForeignKey(User) datetime = models.DateTimeField(default=timezone.now) fruiting_plant = models.ForeignKey(FruitingPlant) was_auto_generated = models.BooleanField(default=False) event_type = models.ForeignKey(EventType) affinity = models.IntegerField(choices=AFFINITY_CHOICES, default=AFFINITY_NEUTRAL) notes = models.TextField(blank=True, null=True) image = ImageField(upload_to=upload_image, blank=True, null=True) def __str__(self): value = '{0} - {1} - {2}'.format(self.datetime, self.event_type, str(self.fruiting_plant)) return value auditlog.register(EventReport) auditlog.register(EventType)
def get_absolute_url(self): return urlresolvers.reverse_lazy( 'adjustment_order_detail', kwargs={'pk': self.pk} ) def __str__(self): return "{} - Person ID: {}".format( self.get_order_type_display(), self.claimant_id ) """ Reports: 1)how much shoes that is in inventory - separate by Brands, style, sku 2)how much money is invested in inventory -separate by brands, style, sku 3)Best sellers 4)best sizes sellers 5)size curve 6) low inventory notifications - sent by notification can be sent by email """ auditlog.register(Shoe) auditlog.register(ShoeAttributes) auditlog.register(Order) auditlog.register(ShoeOrder) auditlog.register(CoverageOrder) auditlog.register(AdjustmentOrder)
from .mixins import TimeStampedSafeDeleteModel class AreaNote(TimeStampedSafeDeleteModel): """ In Finnish: Muistettava ehto """ # In Finnish: Alue # geometry = models.MultiPolygonField(srid=4326, verbose_name=_("Geometry"), null=True, blank=True) geometry = models.MultiPolygonField(srid=4326, null=True, blank=True) # In Finnish: Kommentti note = models.TextField(verbose_name=_("Note"), null=True, blank=True) user = models.ForeignKey(User, verbose_name=_("User"), related_name="+", on_delete=models.PROTECT) recursive_get_related_skip_relations = ["user"] class Meta: verbose_name = pgettext_lazy("Model name", "Area note") verbose_name_plural = pgettext_lazy("Model name", "Area notes") auditlog.register(AreaNote) field_permissions.register(AreaNote)
from django.core.urlresolvers import reverse return reverse('book', args=[self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class BookSource(Model): book = ForeignKey(Book) source = ForeignKey(Source) link = URLField(null=True, blank=True) def __str__(self): return "{0} - {1}".format(self.book.__str__(), self.source.__str__()) #Auditing auditlog.register(Author) auditlog.register(Contributor) auditlog.register(Publisher) auditlog.register(Review) auditlog.register(Category) auditlog.register(Tag) auditlog.register(Language) auditlog.register(Format) auditlog.register(Source) auditlog.register(Book) auditlog.register(Book.categories.through) auditlog.register(Book.availability.through) auditlog.register(Book.formats.through)
from django.apps import apps from django.contrib import admin from auditlog.registry import auditlog from zaakmagazijn.utils.admin import ReadOnlyHistoryModelAdmin app = apps.get_app_config('rsgb') for model_name, model in app.models.items(): admin.site.register(model, ReadOnlyHistoryModelAdmin) auditlog.register(model)
from django.db import models from auditlog.registry import auditlog # Create your models here. class InfoAbst(models.Model): nome = models.CharField(max_length=100) telefone = models.CharField(max_length=15, help_text="Seguir o formato como exemplo: (83)11111-2222") cpf = models.PositiveIntegerField(max_length=11, help_text="Digitar apenas numeros", unique=True) class Meta: abstract = True class Funcionario(InfoAbst): matricula = models.CharField(max_length=5, help_text="Digitar apenas numeros", unique=True) salario = models.DecimalField(max_digits=7, decimal_places=2, default=0) funcao = models.CharField(max_length=60) setor = models.ForeignKey("setor.Setor") endereco = models.ManyToManyField("enderecos.Endereco") def __unicode__(self): return self.nome auditlog.register(Funcionario)
""" start_date = models.DateField(verbose_name=_("Start date")) end_date = models.DateField(verbose_name=_("End date")) # In Finnish: Viitekorko reference_rate = models.DecimalField(verbose_name=_("Reference rate"), max_digits=10, decimal_places=2) # In Finnish: Viivästyskorko penalty_rate = models.DecimalField(verbose_name=_("Penalty rate"), max_digits=10, decimal_places=2) class Meta: verbose_name = pgettext_lazy("Model name", "Interest rate") verbose_name_plural = pgettext_lazy("Model name", "Interest rates") def __str__(self): return "{} - {}".format(self.start_date, self.end_date) auditlog.register(CollectionLetter) auditlog.register(CollectionLetterTemplate) auditlog.register(CollectionNote) auditlog.register(CollectionCourtDecision) auditlog.register(InterestRate) field_permissions.register(CollectionLetter, exclude_fields=["lease"]) field_permissions.register(CollectionNote, exclude_fields=["lease"]) field_permissions.register(CollectionCourtDecision, exclude_fields=["lease"])
from django.db import models from auditlog.registry import auditlog # Create your models here. class Itens(models.Model): nome = models.CharField(max_length = 20) descricao = models.CharField(max_length = 50) valor = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __unicode__(self): return self.nome auditlog.register(Itens)
@property def duration(self): return self.end - self.start def __str__(self): return self.student.full_name class TrainingRequest(models.Model): class Meta: verbose_name = 'Training request' user = models.ForeignKey(User, models.CASCADE, related_name='training_requests') start = models.DateTimeField() end = models.DateTimeField() type = models.IntegerField(choices=Type.choices) level = models.IntegerField(choices=Level.choices) remarks = models.TextField(null=True, blank=True) @property def duration(self): return self.end - self.start def __str__(self): return self.user.full_name auditlog.register(TrainingSession)
return "%s - %s" % (self.bank.name, self.branch_name) class Position(models.Model): class Meta: ordering = ['name'] name = models.CharField(max_length=64, unique=True) description = models.TextField(blank=True) history = AuditlogHistoryField() def __str__(self): return self.name auditlog.register(Position) class Branch(models.Model): class Meta: ordering = ['name'] name = models.CharField(max_length=64, unique=True) location = models.TextField(max_length=64, blank=True) def __str__(self): return self.name class NextOfKin(PermanentModel):
type = models.CharField(max_length=100) created_by = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) updated_by = models.IntegerField(blank=True, null=True) updated_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: db_table = 'C_CATEGORY' class Discount(models.Model): name = models.CharField(max_length=100) rate = models.FloatField() created_by = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) updated_by = models.IntegerField(blank=True, null=True) updated_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: db_table = 'C_DISCOUNT' auditlog.register(Category) auditlog.register(Discount)
related_name="finding") engagement = models.ForeignKey(Engagement, null=True, blank=True, related_name="engagement") test = models.ForeignKey(Test, null=True, blank=True, related_name="test") is_authn_provider = models.BooleanField( default=False, verbose_name="Authentication Provider") url = models.URLField(max_length=2000, null=True, blank=True) def __unicode__(self): return self.cred_id.name + " (" + self.cred_id.role + ")" # Register for automatic logging to database auditlog.register(Dojo_User) auditlog.register(Endpoint) auditlog.register(Engagement) auditlog.register(Finding) auditlog.register(Product) auditlog.register(Test) auditlog.register(Risk_Acceptance) auditlog.register(Finding_Template) auditlog.register(Cred_User) # Register tagging for models tag_register(Product) tag_register(Test) tag_register(Finding) tag_register(Engagement) tag_register(Endpoint)
class ItensVerificacao(ModeloBase): historico = AuditlogHistoryField() descricao = models.TextField('Descrição') item = models.SmallIntegerField('Item', default=0) grupo = models.ForeignKey(GrupoVerificacao, on_delete=models.CASCADE, related_name="itens_de_verificacao") def __str__(self): return f'{self.item} - {self.descricao}' class Meta: verbose_name = 'Item de Verificação' verbose_name_plural = 'Itens de Verificação' @receiver(pre_save, sender=ItensVerificacao) def itens_pre_save(instance, *_args, **_kwargs): if not instance.item: if ItensVerificacao.objects.exists(): instance.item = ItensVerificacao.objects.latest('item').item + 1 else: instance.item = 1 auditlog.register(ModeloAteste) auditlog.register(GrupoVerificacao) auditlog.register(ItensVerificacao)
# In Finnish: Selite description = models.TextField(verbose_name=_("Description"), null=True, blank=True) # In Finnish: Päätös decision = models.ForeignKey( "leasing.Decision", verbose_name=_("Decision"), related_name="+", null=True, blank=True, on_delete=models.PROTECT, ) recursive_get_related_skip_relations = ["contract", "decision"] class Meta: verbose_name = pgettext_lazy("Model name", "Contract change") verbose_name_plural = pgettext_lazy("Model name", "Contract changes") auditlog.register(Contract) auditlog.register(ContractChange) auditlog.register(Collateral) field_permissions.register(Contract, exclude_fields=["lease"]) field_permissions.register(ContractChange, exclude_fields=["contract"]) field_permissions.register(Collateral, exclude_fields=["contract"])
from django.db import models from auditlog.registry import auditlog # Create your models here. class Itens(models.Model): nome = models.CharField(max_length=20) descricao = models.CharField(max_length=50) valor = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __unicode__(self): return self.nome auditlog.register(Itens)
from auditlog.registry import auditlog from django.db import models from ..users.models import User from ..events.models import Event class Feedback(models.Model): class Meta: verbose_name = 'Feedback' verbose_name_plural = 'Feedback' controller = models.ForeignKey(User, models.SET_NULL, null=True, blank=True, related_name='feedback') controller_callsign = models.CharField(max_length=16, null=True, blank=True) pilot = models.ForeignKey(User, models.SET_NULL, null=True, related_name='feedback_given') pilot_callsign = models.CharField(max_length=16, null=True, blank=True) rating = models.IntegerField() comments = models.TextField() event = models.ForeignKey(Event, models.SET_NULL, null=True, blank=True, related_name='feedback') created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def __str__(self): if self.controller is None: return 'General ARTCC Feedback' else: return self.controller.full_name auditlog.register(Feedback, exclude_fields=['created'])
def is_master_exist(self): if self.is_master: return True return (PlanUnit.objects.filter(lease_area=self.lease_area, identifier=self.identifier, is_master=True).count() > 0) @property def is_master_newer(self): if not self.is_master: plan_unit = PlanUnit.objects.filter(lease_area=self.lease_area, identifier=self.identifier, is_master=True).first() if plan_unit: return plan_unit.modified_at > self.modified_at return False auditlog.register(LeaseArea) auditlog.register(LeaseAreaAddress) auditlog.register(ConstructabilityDescription) auditlog.register(Plot) auditlog.register(PlanUnit) field_permissions.register(LeaseArea, exclude_fields=["lease"]) field_permissions.register(LeaseAreaAddress, exclude_fields=["lease_area"]) field_permissions.register(ConstructabilityDescription, exclude_fields=["lease_area"]) field_permissions.register(Plot, exclude_fields=["lease_area"]) field_permissions.register(PlanUnit, exclude_fields=["lease_area"])
from django.db import models from auditlog.registry import auditlog # Create your models here. class Setor(models.Model): nome = models.CharField(max_length = 15) descricao = models.CharField(max_length = 50) def __unicode__(self): return self.nome auditlog.register(Setor)
from sme_coad_apps.users.models import User from ..models import Divisao from ..models_abstracts import TemNome, ModeloBase class Nucleo(ModeloBase, TemNome): historico = AuditlogHistoryField() sigla = models.CharField('Sigla', max_length=20, unique=True) divisao = models.ForeignKey(Divisao, on_delete=models.PROTECT) chefe = models.ForeignKey(User, on_delete=models.PROTECT, related_name='chefe_nucleo', blank=True, null=True) suplente_chefe = models.ForeignKey(User, on_delete=models.PROTECT, related_name='suplente_chefe_nucleo', blank=True, null=True) def __str__(self): return f'{self.divisao.sigla}/{self.sigla}-{self.nome}' class Meta: verbose_name = 'Núcleo' verbose_name_plural = 'Núcleos' auditlog.register(Nucleo)
return reverse_lazy('update_payment', kwargs={'pk': self.payment.pk}) def delete(self, delete_payment=True, *args, **kwargs): if delete_payment and self.payment: self.payment.delete(delete_method=False) return super(EsewaPayment, self).delete(*args, **kwargs) class ReceiptData(models.Model): name = models.CharField(max_length=255) from_no = models.IntegerField() to_no = models.IntegerField() remarks = models.TextField(null=True, blank=True) active = models.BooleanField(default=False) @classmethod def find(cls, no): return cls.objects.get(from_no__lte=no, to_no__gte=no) def __str__(self): return '%s [%d-%d]' % (self.name, self.from_no, self.to_no) class Meta: verbose_name_plural = 'Receipt Data' auditlog.register(DirectPayment) auditlog.register(EsewaPayment) auditlog.register(BankDeposit) auditlog.register(BankAccount)
blank=True, default='') user = models.ForeignKey('auth.User', on_delete=models.PROTECT, verbose_name=_("Właściciel")) date = models.DateTimeField(verbose_name=_("Data"), auto_now_add=True) datemod = models.DateTimeField(verbose_name=_("Data Mod."), auto_now=True) def __unicode__(self): return self.caliber class Meta: ordering = ['caliber'] auditlog.register(caliber) class diameter(models.Model): #all bullets diameters diameter = models.CharField(verbose_name=_("Kalibracja [in]"), max_length=5, unique=True, blank=False) comment = models.TextField(verbose_name=_("Komentarz"), max_length=125, blank=True, default='') user = models.ForeignKey('auth.User', on_delete=models.PROTECT, verbose_name=_("Właściciel")) date = models.DateTimeField(verbose_name=_("Data"), auto_now_add=True)
action = kwargs.pop('action', None) if action == 'pre_add': patient.scheduledProcedures.filter(performDate__isnull = True).delete() elif action == 'post_add': for schedule in patient.schedules.all(): for procedure in schedule.procedures.all(): dates = calcDates(procedure.frequency ) for date in dates: try: PatientScheduleProcedure.objects.create(patient = patient, scheduleProcedure = procedure, date = date) except Exception as err: print (err) m2m_changed.connect(ptSchedule_changed, sender=Patient.schedules.through) auditlog.register(Schedule) auditlog.register(Ward) auditlog.register(Patient) auditlog.register(Bed) auditlog.register(Appointment)
VATIS = 'vATIS', 'vATIS' SOP = 'SOP', 'SOP' LOA = 'LOA', 'LOA' MAVP = 'MAVP', 'MAVP' MISC = 'Misc', 'Misc' class Resource(models.Model): class Meta: verbose_name = 'Resource' name = models.CharField(max_length=128) category = models.CharField(max_length=16, choices=Category.choices) path = models.FileField(upload_to='resources/') updated = models.DateTimeField(auto_now=True) @property def extension(self): name, extension = os.path.splitext(self.path.name) return extension @property def size(self): return os.path.getsize(self.path.path) def __str__(self): return self.name auditlog.register(Resource, exclude_fields=['updated'])
from django.db import models from auditlog.registry import auditlog # Create your models here. class Servico(models.Model): descricao = models.CharField(max_length = 30) valor = models.DecimalField(max_digits = 8, decimal_places = 2) setor = models.ForeignKey('setor.Setor') def __unicode__(self): return self.descricao auditlog.register(Servico)
from django.db import models from django.contrib.auth.models import User from auditlog.registry import auditlog # Create your models here. class OKR(models.Model): issuer = models.ForeignKey(User, on_delete=models.CASCADE) quarter = models.CharField(max_length=10) year = models.CharField(max_length=10) content = models.TextField(blank='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return '{}-{}-{}'.format(self.year, self.quarter, self.issuer.username) auditlog.register(OKR, exclude_fields=['created_at', 'updated_at'])
from django.apps import apps from django.contrib import admin from auditlog.registry import auditlog from zaakmagazijn.utils.admin import ReadOnlyHistoryModelAdmin app = apps.get_app_config('rgbz') for model_name, model in app.models.items(): admin.site.register(model, ReadOnlyHistoryModelAdmin) # The "_inhoud" field is excluded because it retrieves data from the DMS. auditlog.register(model, exclude_fields=['_inhoud'])
def tearDown(self): # Re-register for future tests auditlog.register(SimpleModel)
from django.db import models from auditlog.registry import auditlog from geoposition.fields import GeopositionField from localflavor.br.br_states import STATE_CHOICES # Create your models here. class Endereco(models.Model): rua = models.CharField(max_length=255) bairro = models.CharField(max_length = 20) cep = models.CharField(max_length = 12) cidade = models.CharField(max_length=255) estado = models.CharField(max_length=2, null=True, blank=True, choices=STATE_CHOICES) class Meta: verbose_name, verbose_name_plural = u"Sua Classe" , u"Enderecos" ordering = ('rua',) def __unicode__(self): return self.rua auditlog.register(Endereco)
self.mount_plans.values_list("location", flat=True), self.road_marking_plans.values_list("location", flat=True), self.signpost_plans.values_list("location", flat=True), self.traffic_light_plans.values_list("location", flat=True), self.traffic_sign_plans.values_list("location", flat=True), self.additional_sign_plans.values_list("location", flat=True), )) def derive_location_from_related_plans(self, buffer: int = 5): """ Derive unified location polygon based on related plan models. Buffer the individual points with N meters. :param buffer: Buffer radius """ locations = self._get_related_locations() if len(locations) == 0: self.location = None else: location_polygons = MultiPolygon( [p.buffer(buffer) for p in self._get_related_locations()], srid=settings.SRID, ) area = location_polygons.convex_hull self.location = MultiPolygon(area, srid=settings.SRID) self.save(update_fields=["location"]) auditlog.register(Plan)
reporter = models.ForeignKey(User, editable=False) notes = models.ManyToManyField(Notes, editable=False) created = models.DateTimeField(null=False, editable=False, default=now) def __unicode__(self): return "Risk Acceptance added on %s" % self.created.strftime( "%b %d, %Y") def filename(self): return os.path.basename(self.path.name) \ if self.path is not None else '' # Register for automatic logging to database auditlog.register(Dojo_User) auditlog.register(Endpoint) auditlog.register(Engagement) auditlog.register(Finding) auditlog.register(Product) auditlog.register(Test) auditlog.register(Risk_Acceptance) admin.site.register(Test) admin.site.register(Finding) admin.site.register(Engagement) admin.site.register(Risk_Acceptance) admin.site.register(Check_List) admin.site.register(Test_Type) admin.site.register(Endpoint) admin.site.register(Product)
from auditlog.models import AuditlogHistoryField from auditlog.registry import auditlog from .contrato import Contrato from ...core.models_abstracts import ModeloBase from django.db import models class DotacaoValor(ModeloBase): historico = AuditlogHistoryField() contrato = models.ForeignKey(Contrato, on_delete=models.CASCADE, related_name="dotacoes") dotacao_orcamentaria = models.TextField('Dotação Orçamentária', default='') valor = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): return f'{self.contrato.termo_contrato} - {self.dotacao_orcamentaria} - R${self.valor}' class Meta: verbose_name = 'Dotação Orçamentária' verbose_name_plural = 'Dotações Orçamentárias' auditlog.register(DotacaoValor)
# Create your models here. class University(models.Model): history = AuditlogHistoryField(pk_indexable=False) UniversityId = models.IntegerField(primary_key=True) UniversityName = models.CharField(max_length=45) UniversityAddress = models.CharField(max_length=75) FormationDate = models.DateField() def __unicode__(self): return self.UniversityName class Meta: db_table='university' auditlog.register(University) class Department(models.Model): history = AuditlogHistoryField(pk_indexable=False) DepartmentId = models.IntegerField(primary_key=True) DepartmentName = models.CharField(max_length=45) DepartmentHead = models.CharField(max_length=45) DepartmentPhone = models.IntegerField() UnivId = models.ForeignKey(University) def __unicode__(self): return self.DepartmentName class Meta: db_table='department' unique_together=(("DepartmentId", "DepartmentName"),)
self.first_name, self.last_name, self.mothers_last_name) return full_name.strip() def get_first_name_and_first_lastname(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '{} {}'.format(self.first_name, self.last_name) return full_name.strip() def get_complete_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '{} {} {}'.format(self.first_name, self.last_name, self.mothers_last_name) return full_name.strip() def __str__(self): name = self.get_full_name() if self.first_name else self.username return name class Meta: verbose_name = _('Usuario') verbose_name_plural = _('Usuarios') ordering = ['-date_joined'] auditlog.register(CustomUser)
('C', 'Credito'), ) STATUS_CHOICES = ( ('A', 'Aberta'), ('F', 'Fechada'), ('P', 'Pendente'), ) SETOR_CHOICES = ( ('H', 'Software'), ('S', 'Hardware'), ) numero = models.AutoField(primary_key=True) dataEnt = models.DateField() dataSaida = models.DateField(blank = True, null = True) status = models.CharField(max_length = 1, choices = STATUS_CHOICES, verbose_name = 'Status') pago = models.CharField(max_length = 1, choices = PAGO_CHOICES, verbose_name = 'Pago') formPag = models.CharField(max_length = 1, choices = FORMA_PAG_CHOICES, verbose_name = 'Forma Pagamento', blank = True, null = True) setor = models.CharField(max_length = 1, choices = SETOR_CHOICES, verbose_name = 'Setor', blank = True, null = True) servico = models.ManyToManyField('servicos.Servico') item = models.ManyToManyField('itens.Itens', blank = True) cliente = models.ForeignKey('clientes.Cliente') Observacoes = models.TextField(max_length = 100, blank = True, null = True) auditlog.register(Ordem_Servicos)
A model that is a proxy for another model. """ class Meta: proxy = True class RelatedModel(models.Model): """ A model with a foreign key. """ related = models.ForeignKey('self') history = AuditLogHistoryField() class ManyRelatedModel(models.Model): """ A model with a many to many relation. """ related = models.ManyToManyField('self') history = AuditLogHistoryField() auditlog.register(SimpleModel) auditlog.register(AltPrimaryKeyModel) auditlog.register(ProxyModel)