Saravanan666/pypi-org huggingface dataset:
Package: django-modelformhistory
Django ModelForm Historydjango-modelformhistory will save your modelform updates and store the human-readable values. The main goal is only to show the users what has been updated on a modelForms. If you search for a more lowlevel history app, consider using django-reversion or django-simple-historyWarningThis package is under developpement. It has poor features and may be unstable. Don't use it in production yet.RequirementsDjango 1.10.* / Django 1.11.*Tested under python 2.7 and 3.6Installpip install django-modelformhistoryThen, addmodelformhistoryto INSTALLED_APPSUsageInherit your ModelForm withHistoryModelFormMixinfrommodelformhistory.formsimportHistoryModelFormMixinclassMyModelForm(HistoryModelFormMixin,forms.ModelForm):passYou can get the user that has made the change by :Either pass therequeston the form init, then the request.user will be automatically sent to the new history Entryor implement aget_history_usermethod on your ModelForm that will return aauth.UserobjectTODOProvide generic views to see history by object, user & bothImprove docQuerying models history easilyAdd more support and tests for filefield, booleanFR translationChangeLog1.0.11 2019-06-27Catch Validation error and log error1.0.9 2019-06-26Truncate object_repr charfield length to 200 max chars1.0.7 2019-06-25Added localisation files to package1.0.6 2019-06-19Remove tests from packaging1.0.5 2019-06-19Added docstringsAddedmodels.HistoryBaseModel.log_custom_historyEntry.content_objectis now mandatory1.0.4 2019-06-17Added support for BooleanField and FileField1.0.3 2019-06-17Added more coverageAdded FR translationAdded HistoryBaseModel1.0 2019-06-14Initial Release
Package: django-modelhandler
A python logging handler that saves logs into django model. That’s it.InstallationVia pip:pipinstalldjango-modelhandlerUsageAddmodelhandlerto your INSTALLED_APPS, then, configure log handler in your desired way.
For example, using dictConfig:{'version':1,'handlers':{'modelhandler':{'class':'modelhandler.handlers.LogModel','level':'ERROR'}},'loggers':{'my_logger':{'handlers':['modelhandler'],'level':'ERROR'}}}Run migrations that will create aLogmodel:pythonmanage.pymigrateAnd now you can start logging in django model.Getting logs:frommodelhandler.modelsimportLog# Get the latest loglog=Log.objects.latest()log.name# logger namelog.level# logging level integerlog.levelname# logging level as string (DEBUG, INFO, etc.)log.message# the log messagelog.traceback# traceback, if exists. default: Nonelog.filename# filename (with ext) where the log was sentlog.funcName# function name where the log was sentlog.created# log creation datetimelog.formatted# the log message as if it was written in file. (with [datetime] [level] etc.)If you have a django admin enabled, then you can browse your logs on model Log of application modelhandler.
It has a customized modeladmin to enabale filtering by logger name and levelname, and searching by message.If you would like to customize a log model (to alter models Meta), then just subclass amodelhandler.models.Logmodel, do whatever you want and add your model to LogModel handler parameters:'handlers':{'modelhandler':{'class':'modelhandler.handlers.LogModel','model':'path.to.your.model''level':'ERROR'}}If you using celery in your project then you might want to add some model cleaning tasks inCELERYBEAT_SCHEDULE:CELERYBEAT_SCHEDULE={'cleanup_day':{'task':'modelhandler.tasks.cleanup_day','schedule':timedelta(days=1)},# OR'cleanup_week':{'task':'modelhandler.tasks.cleanup_week','schedule':timedelta(days=7)},# OR'cleanup_month':{'task':'modelhandler.tasks.cleanup_month','schedule':timedelta(days=30)}}modelhandler.tasks.cleanup_daywill delete all logs that are older than one day from time of task execution.modelhandler.tasks.cleanup_weekandmodelhandler.tasks.cleanup_monthare similar.If you want to customize the time of deletion, there is a taskmodelhandler.tasks.cleanup_logsthat accepts
abeforeparameter that must be a datetime object or None (in this case a value of timezone.now() will be taken).
There is no magic: justLog.objects.filter(created__lte=before).delete()History1.0.0 (2016-06-12)Initial release
Package: django-modelhint
when model definitionimportdjango_modelhintasdd.get_default_mapping().add_reserved_words(doc="")classGroup(models.Model):name=d.CharField(max_length=255,verbose_name="Name",doc="名前")classUser(models.Model):group=d.ForeignKey(Group)name=d.CharField(max_length=255,verbose_name="Name",doc="名前")when viewimportdjango_modelhintasduser=User.objects.get()d.get_mapping(user)# => ChainMap({}, {'name': ChainMap({}, {'doc': '名前'}), 'id': ChainMap({}, {'doc': ''}), 'group': ChainMap({}, {'doc': ''})})d.get_mapping(user)["name"]["doc"]# => '名前'group=Group.objects.get()d.get_mapping(group.user_set)# => ChainMap({}, {'name': ChainMap({}, {'doc': '名前'}), 'id': ChainMap({}, {'doc': ''}), 'group': ChainMap({}, {'doc': ''})})
Package: django-model-history
django-model-historyEnable in any Model class an change history of all inserts, updates and deletesInstallationIn your settings.pyINSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',

    #.....................#

    'model_history',
)Option 1: In your models.pyYou only must to update the parent class of your model.from django.db import models


class MyModel(models.Model):
    ....from model_history.models import ModelHistoryProvider


class MyModel(ModelHistoryProvider):
    ....

...Option 1 example.Option 2: In your models.pyOr you can call directly to the create_history_model_class functionfrom django.db import models


from model_history.models import create_history_model_class, BaseModelHistory

class MyModel(models.Model):
    ....


MyModelHistory = create_history_model_class(MyModel, (BaseModelHistory,))Option 2 example.DevelopmentYou can get the last bleeding edge version of django-model-history by doing a clone
of its git repositorygit clone https://github.com/goinnn/django-model-historyExample projectIn the source tree, you will find a directory calledexample. It contains
a readily setup project that uses django-model-history. You can run it as usual:python manage.py makemigrations
python manage.py syncdb --noinput
python manage.py runserverAccess in a browser tohttp://localhost:8000/0.1.2 (2015-04-24)Fix typo errors0.1.1 (2015-04-24)Fix typo errors0.1.0 (2015-04-24)Initial version
Package: django-model-history-log
django-model-history-logRegister fields updates.WARNINGThis project currently relies on Django signals
(by defaultpost_save,pre_delete, andm2m_changed),
so if you do some bulk action (ie viaqueryset.update()),
any action will not be recorded!InstallInstall package withpipinstalldjango-model-history-logConfigureAddmodel_history.apps.ModelHistoryConfiginto yourINSTALLED_APPS#!pythonINSTALLED_APPS=[..."model_history.apps.ModelHistoryConfig",...]and then run./manage.pymigrateRegister a model at startupYou can register a model for logging at startup usingHistory.registerhelper:classMyAppConfig(AppConfig):name="myapp"defready(self):frommodel_history.modelsimportHistoryfromdjango.contrib.authimportget_user_modelHistory.register(get_user_model(),exclude=["password"])You can register all models with a snippet like thisclassMyAppConfig(AppConfig):default_auto_field="django.db.models.BigAutoField"name="myapp"verbose_name=_("My Website")defready(self):fromdjango.contrib.admin.modelsimportLogEntryfromdjango.contrib.authimportget_user_modelfromdjango.contrib.sessions.modelsimportSessionfrommodel_history.modelsimportHistory,HistoryLogUser=get_user_model()History.register(User,exclude=["password"])formodelinapps.get_models():ifmodelnotin[LogEntry,History,HistoryLog,Session,User]:History.register(model)UsageLog a single instanceYou can log a single instance changes with theHistoryManager.log()method:instance=MyInstance.objects.get(...)...History.objects.log(instance)Paramsinstance:models.Model= instance to logexclude:list[str] | None= exclude these fields from loggingserializer_class:rest_framework.serializers.Serializer | None= use this serializer instanceQuery a logfromdjango.contrib.authimportget_user_modelhistory=History.objects.fetch(User.objects.first())history.logs.all()fetch()always returns an History instance, regardless it is saved on db or not.
You must rely on it'spkvalue or you should check forlogs.CHANGES0.2.1Docs update0.2.0Rename project to django-model-history-log (sorry, no migration path)Reformat all codebase with blackUpdate isort/flake8 configUse django JSONFieldRemove default ordering, use only in adminAdd register/unregister actionsAdd HistoryQuerySet.fetch apiSave str(source) as {History,HistoryLog}.labelAdd en translationsAdd it translations0.1.1added missingon_deleteon HistoryRow.history field0.1.0initial relase
Package: django-model-history-tracker
Django Model History TrackerDjango Model History Tracker is a utility that tracks changes to model instances and saves the history of updates. This can be helpful for auditing purposes or for generating reports about changes over time.FeaturesTrack creation, update, and deletion of model instancesStore historical data in a separateHistorymodelEasy integration with existing Django models using a mixinInstallationInstall the package using pip:pip install django-model-history-trackerAdd'django_model_history_tracker'to yourINSTALLED_APPSinsettings.py:INSTALLED_APPS=[...'django_model_history_tracker',...]pythonmanage.pymigrate## UsageTouseDjangoModelHistoryTracker,simplyinherittheHistoryTrackerMixininanymodelyouwanttotrack:fromdjango.dbimportmodelsfromdjango_model_history_tracker.mixinsimportHistoryTrackerMixinclassExampleModel(HistoryTrackerMixin,models.Model):field1=models.CharField(max_length=100)field2=models.IntegerField()That's it! Your model will now automatically track changes and store them in the History model.AccessingHistoryYoucanaccessthehistoryofatrackedmodelinstanceusingthegenericrelation:history=example_model_instance.history_set.all()Eachhistoryentrywillhavethefollowingfields:action:Theactionthatoccurred('create','update',or'delete')timestamp:Thetimestampofwhentheactionoccurredchanges:AJSONfieldcontainingthechangesmadetotheinstanceContributingContributionsarewelcome!PleasefeelfreetosubmitissuesorpullrequestsontheGitHubrepository.LicenseThisprojectislicensedundertheMITLicense.SeetheLICENSEfilefordetails.
Package: django-model-hooks
django-model-hooksModel hooks for Django.RationaleAdd persistent receivers with logging for django model signals.SupportSupports: Python 3.10.Supports Django Versions: 4.2.7Installation$pipinstalldjango-model-hooksUsageAddmodel_hookstoINSTALLED_APPS.Run migrations:pythonmanage.pymigrateAdd a modulemodel_hooks_registryto one or more of your apps. Decorate any function you want to be triggered by
a hook with themodel_hookdecorator.Post serialized data to a rest endpoint on creation of amyapp.MyModelinstance:# model_hooks_registry.pyimportjsonimportrequestsfrommodel_hooks.decoratorsimportmodel_hookfrommodel_hooks.eventsimportcreate_eventfrommyapp.modelsimportMyModelfrommyapp.serializersimportserializer@model_hook(MyModel,create_event,serializer=serializer)defhook_create(instance,payload,**kwargs):requests.post(kwargs.get('rest_url'),data=json.dumps(payload))Or specify a special tag for the triggering of the function call:# model_hooks_registry.pyimportjsonimportrequestsfrommodel_hooks.decoratorsimportmodel_hookfrommodel_hooks.eventsimportcreate_eventfrommyapp.modelsimportMyModelfrommyapp.serializersimportserializer@model_hook(MyModel,create_event,serializer=serializer,tag='rest')defhook_create(instance,payload,**kwargs):requests.post(kwargs.get('rest_url'),data=json.dumps(payload))You may also define a custom event:# model_hooks_registry.pyimportjsonimportrequestsfrommodel_hooks.decoratorsimportmodel_hookfrommodel_hooks.eventsimportHookEventfrommyapp.modelsimportMyModelfrommyapp.serializersimportserializercustom_event=HookEvent('custom_event')@model_hook(MyModel,custom_event,serializer=serializer)defhook_custom(instance,payload,**kwargs):requests.post(kwargs.get('rest_url'),data=json.dumps(payload))Trigger the event:frommodel_hooks.signalsimporthook_eventfrommyapp.model_hooks_registryimportcustom_eventfrommyapp.modelsimportMyModelinstance=MyModel.objects.get(pk=1)hook_event.send(MyModel,model=MyModel,instance=instance,event=custom_event)Now go to the Django admin and add the hooks for the appropriate models and events.Prune the log table:pythonmanage.pylog_prune
Package: django-model-ident
==================
django-model-ident.. image::https://badge.fury.io/py/django-model-ident.png:target:https://badge.fury.io/py/django-model-ident.. image::https://travis-ci.org/ckirby/django-model-ident.png?branch=master:target:https://travis-ci.org/ckirby/django-model-ident.. image::https://coveralls.io/repos/ckirby/django-model-ident/badge.png?branch=master:target:https://coveralls.io/r/ckirby/django-model-ident?branch=masterdjango-model-identprovides a quick lookup for django models by pk only.
Instead of writing ModelName.objects.get(pk=pk) write ModelName.ident_(pk)ProjectThe project can be found athttps://github.com/ckirby/django-model-identRequirementsDjango 1.11+Python 3.4+UsageAdd 'model-ident' to your INSTALLED_APPSHow Does It WorkON ready() django-model-ident monkey patches all the models found in your INSTALLED_APPS with the method ident_(pk).
This calls ._base_manager.get(pk=pk). We use _base_manager so as not to get confused by changes in ModelManagers.
Package: django-modelish
Because programmers are lazy…Modelish is a quick attempt to save a few keystrokes. Many data modeling tools
are a GUI nightmare, with dropdowns and lots of buttons. But sometimes,
especially when you are sketching something out, writing out full Django models
can be a bit tedious.Modelish will parse a file with a simplified model declaration in a flavor of
YAML and generate Python code for model definition.Normally I would say source code generation is a “Bad Idea”, but really even
in Python, Django models are a mostly declarative syntaxQuickstartInstall django-predicate:pip install django-modelishYou can then start banging out models like thisPoll:doc:This is the poll modelquestion:type:charmax_length:200pub_date:type:datetimeargs:date publishedChoice:poll:type:fkargs:[Poll]choice_text-char:max_length:200votes:type:intYou then just use the CLI tool:modelish path-to-file.ymlThis will generate code like this:classPoll(models.Model):"""This is the poll model"""pub_date=models.DateTimeField('date published')question=models.CharField(max_length=200,blank=True)classChoice(models.Model):choice_text=models.CharField(max_length=200,blank=True)poll=models.ForeignKey('Poll')votes=models.IntegerField()SyntaxThe syntax is pretty simple:<ModelName>:
    [doc: docstring]
    <fieldname>[-type-alias]:
        [type: type-alias],
        [args: arglist],
        kwarg: valueThe field type is represented by a shortened ‘type’ alias so ‘char’ becomes
‘models.CharField’ etc (see grammarish below).The type can be specified one of two ways, either following the field name with
a hyphen, or explicitly declared as atypein the field definition.Positional args to the model specified as an explicit list in square brackets,
or as a comma delimited string.The remaining block of the field definition consists of kwarg/value pairs.Working with grammarishModelish works with a grammar composed of type aliases and defaults. The standard
types are:auto:AutoFieldbigint:BigIntegerFieldbool:BooleanFieldchar:CharFielddate:DateFielddatetime:DateTimeFielddecimal:DecimalFieldemail:EmailFieldfile:FileFieldfloat:FloatFieldimage:ImageFieldint:IntegerFieldip:IPAddressFieldgip:GenericIPAddressFieldnbool:NullBooleanFieldpint:PositiveIntegerFieldpsint:PositiveSmallIntegerFieldslug:SlugFieldsint:SmallIntegerFieldtext:TextFieldtime:TimeFieldurl:URLFieldfk:ForeignKeym2m:ManyToManyFieldtimestamp:DateTimeFieldFor each type - a set of default kwargs is defined in the grammar asdefaults:defaults:bool:default:truechar:max_length:100blank:truenbool:null:truetimestamp:auto-now:trueThis default grammar can be replace, or enhanced by passing your own yaml files
to the command.  Use--grammarto replace the default grammer, and use--extra-grammarto merge in and update the default grammer with your own
additions or changes.That’s it - this isn’t meant to be any sort of full featured model builder or
data modeler, it is just a simple DSLish bootstrap tool to give you
a models.py starting point with a little less typing.
Package: django-model-logging
# django-model-loggingLogging for changes made to Django model instances.## Installation`pip install django-model-logging`Add `model_logging` to your `INSTALLED_APPS`.## Usage#### Low-level use```pythonfrom model_logging.models import LogEntryLogEntry.objects.log(log_entry_creator,operation,model,user,json_data,)```The parameters are as follows:* `log_entry_creator`:  The user who made this change.* `operation`:  One of `LogEntry.OPERATION_ADDED`, `LogEntry.OPERATION_REMOVED`,or `LogEntry.OPERATION_MODIFIED`.* `model`:  The path to the model being logged (e.g. 'users.models.User').* `user`:  The user to which the model instance belongs.* `json_data`:  A full or partial JSON representation of data on the model instance.#### Medium-level useTo add methods to a view(set) that can be used to straightforwardly log changes:```pythonfrom model_logging.views import LoggingMethodMixinclass AViewOrViewset(LoggingMethodMixin, ModelViewSet):def _get_logging_user(self):# Override this method to return a suitable# value for the `user` parameter above.return self.instance.user  # or similardef extra_data(self):# Overriding this isn't mandatory, it's just a hookreturn {'any additional data': 'you wish to log'}```The class now has access to the following:```pythondef log(self, operation, data):# A simplified version of LogEntry.objects.log,# with some parameters pre-filled. The return# value of extra_data() will be added to the# supplied data.def _log_on_create(self, serializer):# Log a LogEntry.OPERATION_ADDED change, using# the log() method above.def _log_on_update(self, serializer):# Log a LogEntry.OPERATION_MODIFIED change, using# the log() method above.def _log_on_destroy(self, instance):# Log a LogEntry.OPERATION_DELETED change, using# the log() method above.```More abstract still:#### High-level useA viewset can log its own changes!```pythonfrom model_logging.views import LoggingViewSetMixinclass AVeryShinyViewSet(LoggingViewSetMixin, ModelViewSet):def _get_logging_user(self):# Override this method to return a suitable# value for the `user` parameter above.return self.instance.user  # or similardef extra_data(self):# Overriding this isn't mandatory, it's just a hookreturn {'any additional data': 'you wish to log'}```This mixin is a wrapper around `LoggingMethodMixin` that calls the appropriate loggingmethods during `perform_create`, `perform_update` and `perform_destroy`.
Package: django-model-logs
Model logs is a Django app for storing changes of yours objectsQuick startAdd “model_log” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'model_log',
]Runpython manage.py migrateto create the “model_logs” models.For adding or excluding the models you want to log, in thesettings.py:MODELS_FOR_LOGGING = (
    'app.ClassName',    # logging only for this model
    'another_app'     # logging of all models in this app
)

MODELS_FOR_EXCLUDE = (
    'app.ClassName',    # excluding from logging only for this model
)To override Django’s default view to show the history of a log, use LogModelAdmin instead of ModelAdmin:class ExampleAdmin(LogModelAdmin):
    pass
Package: django-model-mail
Django package that helps to create emails from models (e.g. for admins’ notifications)Free software: MIT licenseFeaturesTODODeployingA reminder for the maintainers on how to deploy.
Make sure all your changes are committed (including an entry in HISTORY.rst).
Then run:$ poetry version patch # possible: major / minor / patch
$ git push
$ git push --tagsTravis will then deploy to PyPI if tests pass.
Package: django-model-mixin
django-model-mixinGitHubTestCheck Demo ProjectCheck the demo repo onGitHubRequirementsPython 3.8+ supported.Django 3.2+ supported.SetupInstall frompip:pipinstalldjango-model-mixinModifysettings.pyby adding the app toINSTALLED_APPS:INSTALLED_APPS=[# ..."model_mixin",# ...]Modify your projectmodels.pywith needed imports and class extends:# ...other imports...frommodel_mixin.modelsimportAuditModelMixin,PublishModelMixinclassMyCustomClass(AuditModelMixin,PublishModelMixin):# ...Execute Django's commandmakemigrationsinside your project's root:pythonmanage.pymakemigrationsFinally, execute Django's commandmigrateinside your project's root:pythonmanage.pymigrateRun Example Projectgitclone--depth=50--branch=django-model-mixinhttps://github.com/DLRSP/example.gitDLRSP/examplecdDLRSP/example
pythonmanage.pyrunserverNow browser the app @http://127.0.0.1:8000
Package: django-modelmultivalue
ModelMultiValueField provides the ability to create sub-forms for foreign models without having to worry about writing
the ModelMultiValueField subclasses.Quick startAdd “modelmultivalue” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'modelmultivalue',
]Add the ModelMultiValueField to a model formAll django version:from django import forms
from modelmultivalue import ModelMultiValueField

class ExampleModelForm(forms.ModelForm):
    class Meta:
        model = Example
        fields = '__all__'

    ForeignKeyField = ModelMultiValueField(model=ForeignKeyfor Django>=1.9:from django import forms
from modelmultivalue import ModelMultiValueField

class ExampleModelForm(forms.ModelForm):
    class Meta:
        model = Example
        fields = '__all__'
        field_classes={
            'ForeignKeyField': ModelMultiValueField
        }
Package: django-model-path-converter
Django Model Path ConverterThe Django Model Path Converter package dynamically creates custom path converters for you models.Free software: MIT licenseDocumentation:https://django-model-path-converter.readthedocs.io.Background story:https://consideratecode.com/django-model-path-convertersQuickstartInstall the latest version:pip install django-model-path-converterImportregister_model_converterand your model in yoururls.py:from model_path_converter import register_model_converter
from .models import MyModelRegister a converter for your model:register_model_converter(MyModel)Use the new converter in your path definitions:path('<my_model:obj>/', views.my_view, name='my-view')Your viewmy_viewwill now receive aMyModelinstance as argument.CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2018-05-11)First release on PyPI.
Package: django-model-prefix
Django Model PrefixA Django package that adds a global or model based database table prefixInstallationInstall using pip:pipinstalldjango-model-prefixAdd model_prefix to your INSTALLED_APPS list. Make sure it is the first app in the listINSTALLED_APPS=['model_prefix',...]UsageGlobal table prefixThe global database table prefix can be configured using theDB_PREFIXsettingDB_PREFIX="foo_"Model table prefixOptionally a model based prefix can also be defined by extending the models meta classclassMeta:db_prefix="bar_"This can be also used in order to disable the global prefix for a specific modelclassMeta:db_prefix=None
Package: django-model-publisher
Django model mixins and utilities for a standard publisher workflow.django-model-publishersupportsDjango1.8 through 1.11 (latest bugfix
release in each series only) on Python 2.7, 3.3 (Django 1.8 only), 3.4, and 3.5.This app is available onPyPI.Getting HelpDocumentation for django-model-publisher is available athttps://django-model-publisher.readthedocs.org.QuickstartInstall django-model-publisher:pip installdjango-model-publisherFeaturesDjango CMS placeholders support.Hvad/Parler support.Restrict user access to publish functions with user permissions.