Saravanan666/pypi-org huggingface dataset:
Package: django-model-auditor
django-model-auditordjango-model-auditor is a Python library for maintaining versions of your django model instances.InstallationUse the package managerpipto install foobar.pipinstalldjango-model-auditorUsageAdd audits in INSTALLED_APPS inside settings.py of your django projectINSTALLED_APPS=['audits.apps.AuditsConfig',]run migration to create auditlog modelpythonmanage.pymigrateChange metaclass of model(for which audit logs are needed) to ModelHistoryMetafromaudits.modelsimportModelHistoryMetafromdjango.dbimportmodelsclassExampleModel(models.Model,metaclass=ModelHistoryMeta):field1=models.CharField(max_length=100)field2=models.CharField(max_length=100)ExampleimportExampleModelobject=ExampleModel(field1="foo",field2="bar")object.save()#will create an entry in auditlog modelobject.field1="Foo"object.field2="Bar"object.save()#will create another entry in auditlog modelobject.field1="FOO"object.field2="BAR"object.save()#will create another entry in auditlog model#To get previous versions of the objectprevious_versions=AuditLog.get_prev_versions(object,limit=2)#By default get_prev_versions return only last_prev_version to#get more versions we need to specify limitlatest_prev_version=previous_versions[0]print("%s%s"%(latest_prev_version.field1,latest_prev_version.field2))# "Foo","Bar"prev_to_prev_version=previous_versions[1]print("%s%s"%(prev_to_prev_version.field1,prev_to_prev_version.field2))# "foo","bar"ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
Package: django-model-cache
# django-model-cacheAn easy-to-use cache for Django models.This code has been developed and used in a production environment for one year.## How to useThere follows some examples of use. For further examples, see `tests/simple/tests.py`.```pythonclass Brand(models.Model):name = models.CharField(max_length=128)cache = CacheController(timeout=None)class Product(models.Model):code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)brand = models.ForeignKey('Brand')name = models.CharField(max_length=255)cache = CacheController(fields=['code', ('brand_id', 'name')], related_fields=['brand'], timeout=None)class Meta:unique_together = ('name', 'brand')# Get a product by pk.product = Product.cache.get(pk=1)# Get a product by a unique key.product = Product.cache.get(code='A001')# Load the related models.product.load_related()```## How to testJust run `tox` or install the dependencies and run `cd tests/ && ./manage.py test`.
Package: django-model-cached-property
django_model_cached_propertyDjango model cached property is useful for caching of property results for more time than lifetime of object during the requestThis package use redis like a caching backend, because redis allow to delete keys by template. It is usefull for caching different keys for different users.Installpip install -U django-model-cached-propertyInstall and configure requirementsInstall redis for caching.sudo apt install redis-serverConfiguresetup.pyof your django project.CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}UsingPackage contains two functions:model_cached_property- it is decorator for class methods, which will cache results of property call for separate records.invalidate_model_cached_property- it is function for invalidation of method on the model record property.model_cached_propertyYou can use this decorator by following way.from django_model_cached_property import model_cached_property

class Article(models.Model):
 
    @model_cached_property
    def comments_count(self):
        return self.comments.count()It means you cache comments count for each record of article in your Django project.You can set up cache timeout 3000 second by following way.class Article(models.Model):
 
    @model_cached_property(timeout=3000)
    def comments_count(self):
        return self.comments.count()By default, caching timeout is 60 second, by you can set up it globally insettings.py.MODEL_CACHED_PROPERTY_TIMEOUT = 300000Additionally, you can use caching of model property with input arguments.
And in this case caching will be evaluated for all input sets of arguments.For example caching by authenticated user.class Article(models.Model):
 
    @model_cached_property
    def __user_in_bookmarks(self, user):
        return self.bookmarks.filter(user=user).exists()
 
    def user_in_bookmarks(self, user):
        return self.__user_in_bookmarks(user) if user.is_authenticated else Falseinvalidate_model_cached_propertyThis function invalidate all cache keys on the property for one model record in database.For examplearticle = get_object_or_404(Article, pk=12)
invalidate_model_cached_property(article, article.comments_count)In this case you invalidate all cached keys for article with primary key 2.WARNING - LimitationLimitation of this caching functionality consists in the fact that you can use it with unique input arguments only.
It means, that will not work with AnonymousUser object, because of in each request information about AnonymousUser object will be different, although it will be called by same user.
Therefore, use it on unique information only.
Package: django-model-choices
Django Model ChoicesDjango Model Choices (DMC) provides a readable and DRY way to specify choices for Django models and forms. Although there are many similar projects available, Django Model Choices is willing to offer the most neat and DRY syntax.FeaturesA classic choices class in Django looks like this:classCharityType(models.Model):SOCIAL='SOC'ENVIRONMENTAL='ENV'EDUCATIONAL='EDU'CHOICES=((SOCIAL,'Social'),(ENVIRONMENTAL,'Environmental'),(EDUCATIONAL,'Educational'),)This is far from being DRY and is also prone to typos and other mistakes. Using Django Model Choices you could do:frommodelchoicesimportChoicesclassCharityType(Choices):SOCIAL=('SOC','Social')ENVIRONMENTAL=('ENV','Environmental')EDUCATIONAL=('EDU','Educational')The value of each choice must be a tuple containing a value for the database and a user readable value, which could also be translation object as in this example.TheCHOICESfield will be generated magically by the metaclass, so you can use it in the model like this:classCharity(models.Model):charity_type=models.CharField(max_length=1,choices=CharityType.CHOICES)The variablesSOCIAL,ENVIRONMENTALandEDUCATIONALcan be used to programmatically represent the choice values. Once the class is created, their values are no longer a tuples, but only the database fields (soCharityType.ENVIRONMENTALis equal to'ENV'). So you can do:charity=Charity()charity.charity_type=CharityType.ENVIRONMENTALcharity.save()Another field generated magically isVALUE_MAPPER. It is a dictionary, where the keys represent the database values and the dictionary values represent the variable name used to declare the options. In our exampleVALUE_MAPPERlook like this:>>>CharityType.VALUE_MAPPER{'SOC':'SOCIAL','ENV':'ENVIRONMENTAL','EDU':'EDUCATIONAL'}This is useful if you need to use the variable names a codes (for a REST API for instance), because the user readable values might be subjects of translation.
Package: django-model-cleanup
Mixins for model cleanup methods and validation error concatenationsFree software: MIT licenseDocumentation:https://django-model-cleanup.readthedocs.io.Features of CleanMixinProvidescleanmethod implementationCall tofull_cleanwill result in call to allclean_*methodsAll methods will get called regardless of validation errors - get all errors at onceAuto mapping of errors to field names based on clean method names, if errors have no error_dictQuickstartInstall Django Model Cleanup:pip install django-model-cleanupAdd mixin in your models and enjoyclean_method collection and error concatenation whenfull_cleanis called:fromdjango.core.exceptionsimportValidationErrorfromdjango.dbimportmodelsfromdjango.utils.translationimportugettext_lazyas_fromdjango_model_cleanupimportCleanMixin,ExtensibleValidationErrorclassSomeModel(CleanMixin,models.Model):lorem=models.CharField(max_length=10,blank=True)defclean_foo(self):raiseValidationError('Foo is bad')defclean_bar(self):raiseExtensibleValidationError({'bar':_('Bar is wrong cause%s>%s!')},code='bar',params=(2,1))defclean_legacy(self):# We can't init ValidationError as one-liner, cause dict + params are not compatible# We need to wrap a message in ValidationError and put that in dict indicating a fieldmsg=_('Bar legacy error%s>%s!')error=ValidationError(msg,code='bar',params=(7,5))raiseValidationError({'bar':error})Each error handling and concatenation is no longer required:# This is not longer required:defclean(self):errors=[]try:self.clean_foo()exceptValidationErrorasex:errors.append(ex)errors=[]try:self.clean_bar()exceptValidationErrorasex:errors.append(ex)errors=[]try:self.clean_legacy()exceptValidationErrorasex:errors.append(ex)iferrors:raiseValidationError(errors)Running TestsDoes the code actually work?::$ pipenv install –dev
$ pipenv shell
$ toxWe recommend usingpipenvbut a legacy approach to creating virtualenv and installing requirements should also work.
Please installrequirements/development.txtto setup virtual env for testing and development.CreditsThis package was created withCookiecutterand thewooyek/cookiecutter-django-appproject template.History0.1.0 (2017-12-05)First release on PyPI.
Package: django-modelclone-next
django-modelclone-nextAllows users to duplicate a model in admin.This is a fork ofhttps://github.com/RealGeeks/django-modelcloneInstallation$ pip install django-modelclone-nextthen:Add'modelclone'toINSTALLED_APPSIn youradmin.pyfiles extend frommodelclone.ClonableModelAdmininstead of
Django'sModelAdminThe models that have admin configuration extendingmodelclone.ClonableModelAdminwill
have a new link on the Change page to duplicate that objectThis links redirects to a page similar to an Add page but with all the fields already
filled with the values from the original object.Note that you still need to save to get a new object. And make sure to edit fields
that must be unique otherwise you will get a validation error.But Django already has a 'save as'Yes, I know. Django Admin has asave_asfeature that adds a new button to your Change page to save a new instance of that
object.I don't like the way this feature works because you will save an identical copy of the
original object (if you don't get validation errors) as soon as you click that link, and
if you forget to make the small changes that you wanted in the new object you will end up
with a duplicate of the existing object.On the other hand, django-modelclone offers an intermediate view, that basically pre-fills
the form for you. So you can modify and then save a new instance. Or just go away without
side effects.RequirementsPython 3Django 2.2, 3.0, 3.1, 3.2 or 4.0Seetox.iniHackingFork therepository on github, make your
changes (don't forget the tests) and send a pull request.To run the tests, install and runTox:$ pip install tox
$ toxYou can also run the sample project to test manually. In this case you'll need to
install Django, or just use one of the virtualenvs tox creates, for example:$ source .tox/py310-django32/bin/activatethen start the server(py310-django32) $ ./manager serveThe app is available onhttp://localhost:8000/admin/,
username and password "admin".
Package: django-model-controller
Model instance tracker.Full documentation for this project available athttp://django-model-controller.readthedocs.ioOverviewCome to a time that you want to able to keep track on each record of data that was created or updated.
This project give you the ability to answer these questions: When this record was created? When this record was updated?
Who created this record? Who updated this record?These are the classes that you can use to extend your classes:ModelAbstractTimeStampMarkermodel datetime create and updateAbstractModelControllermodel datetime and who create and updateFormModelControllerFormform for automatically setup who create and updateViewCreateViewMixinview that used form class extended from ModelControllerForm must extend from CreateViewMixinUpdateViewMixinsimilar to CreateViewMixin but for UpdateViewRequirementsPython (2.7, 3.2, 3.4, 3.5, 3.6)Django (1.8, 1.9, 1.10, 2.x.x, 3.x.x)Quick startInstall using pip:pipinstalldjango-model-controller
Package: django-model-decoupler
Django model decouplerdjango-model-decoupler enables simplification of development and separation of
business logic from presentation and data persistence in Django web framework.InstallWith pipenv:$ pipenv install django-model-decoupleror with pip:$ python -m pip install django-model-decouplerQuick startAdd "model_decoupler" to your INSTALLED_APPS setting like this::INSTALLED_APPS=[...'model_decoupler',]Change your models to inherit frommodel_decoupler.Model:fromdjango.dbimportmodelsimportdecouplerfrompure_python_moduleimportPurePythonClassclassMyModel(decoupler.Model,adaptee=PurePythonClass):attr1=models.Field(...)...Your changed MyModel should be able to act proxy to PurePythonClass from
now.
Package: django-modeldict
ModelDict is a very efficient way to store things like settings in your database. The entire model is transformed into a dictionary (lazily) as well as stored in your cache. It’s invalidated only when it needs to be (both in process and based onCACHE_BACKEND).Quick example usage. More docs to come (maybe?):class Setting(models.Model):
    key = models.CharField(max_length=32)
    value = models.CharField(max_length=200)
settings = ModelDict(Setting, key='key', value='value', instances=False)

# access missing value
settings['foo']
>>> KeyError

# set the value
settings['foo'] = 'hello'

# fetch the current value using either method
Setting.objects.get(key='foo').value
>>> 'hello'

settings['foo']
>>> 'hello'
Package: django-modeldict-rc
ModelDict is a very efficient way to store things like settings in your database. The entire model is transformed into a dictionary (lazily) as well as stored in your cache. It’s invalidated only when it needs to be (both in process and based onCACHE_BACKEND).Quick example usage. More docs to come (maybe?):class Setting(models.Model):
    key = models.CharField(max_length=32)
    value = models.CharField(max_length=200)
settings = ModelDict(Setting, key='key', value='value', instances=False)

# access missing value
settings['foo']
>>> KeyError

# set the value
settings['foo'] = 'hello'

# fetch the current value using either method
Setting.objects.get(key='foo').value
>>> 'hello'

settings['foo']
>>> 'hello'
Package: django-model-docs
Generate docs for django modelsGenerate extensible Markdown documentation for Django models. Developed for
cross-team collaboration when iterating on on data model specifications.User quickstart with an existing Django projectInstall into your project requirements (git+https://github.com/jakekara/django-model-docs.git)Add to the Django settingsINSTALLED_APPS.Generate Markdown documentationYOUR_APPpythonmanage.pygenerate-model-docsYOUR_APPDev quick start# set up a virtual env however you like. here's what I like:python-mvenvvenv../venvbinactivate# set up dev stuffpipinstall-rrequirements.txt# install the package in editable modepipinstall-e.# generate docs for model(s) in the demo appcddemo_django_project
pythonmanage.pygenerate-model-docsdemo_django_appThe output looks like this at the moment:# `demo_django_app`` app`_This file was auto-generated Django Model Docs Generator.  Do not edit this file directly._A demo Django App. Note that this text will be pulled from the app's docstring and used in the default output of`generate-model-docs`.## `person` modelPerson(id, first_name, last_name, shoeStyle)

|    Field   |Description|                                                          Data type                                                         |Nullable|Default|
|------------|-----------|----------------------------------------------------------------------------------------------------------------------------|--------|-------|
|`id`|           |                                                        BigAutoField                                                        |  False |   -   |
|`first_name`|           |                                                          CharField                                                         |  False |   -   |
|`last_name`|           |                                                          CharField                                                         |  False |   -   |
|`shoeStyle`|           |CharField<br><br>Choices (stored value : human readable)<br><br>-`LO`:`LOAFER`<br>-`BO`:`BOOT`<br>-`DR`:`DRESS`<br>|  False |   -   |TestsTests need to be run in the context of thedemo_django_app.cddemo_django_project
pythonmanage.pytestdjango-model-docsTo run the test suite against every supported Python version, use the commandtox(you must have each Python version available to tox). You should see output like:py39:OK(2.44=setup[2.08]+cmd[0.36]seconds)py310:OK(2.04=setup[1.75]+cmd[0.30]seconds)py311:OK(2.19=setup[1.86]+cmd[0.33]seconds)py312:OK(6.02=setup[5.63]+cmd[0.39]seconds)congratulations:)(12.72seconds)If you're usingpyenvto manage versions, you need to runpyenv local 3.9 3.10 3.11 3.12to make these versions accessible to tox from in the project environment.
Package: django-modelduplication
=====Model Duplication=====Django admin have `save_as` feature, but that feature have bug with images field, and sometime you want 100% duplication of a model instance with all other related objects and customization, then `save_as` doesn't fit for that purpose... image:: https://coveralls.io/repos/github/squallcs12/django-modelduplication/badge.svg?branch=master:target: https://coveralls.io/github/squallcs12/django-modelduplication?branch=masterQuick start-----------1. Add "modelduplication" to your INSTALLED_APPS setting like this:.. code-block:: pythonINSTALLED_APPS = [# ...'modelduplication',]2. Define `pre_duplicate` and `post_duplicate` to your models to customize duplication process:.. code-block:: pythonclass Book(models.Model):def pre_duplicate(self, origin, first_level):"""This method use to modify object before `save` on duplication.:type origin models.Model:type first_level bool:param first_level is the root level of duplication:param origin the origin instance"""passdef post_duplicate(self, origin):"""This method is called after finishing the duplication.:type origin models.Model:param origin the origin instance"""pass
Package: django-model-event-actions
django-model-event-actions |latest-version||python-support| |django-support| |pypi| |license|.. start docs includeThis package is a replacement for the builtin Django_ Signals which you can define all of the
events and actions in the model itself and add conditions to determine when they are triggered.
With the help of this package you can track the changed field previous and current values and
determine when an action should trigger by creating an event with the decorators in the model.A simple example will be:.. code-block:: pythonclass User(EventActionModel):
    is_active = models.BooleanField()

    @PostSaveEvent(field='is_active', prev=False, now=True)
    def user_deactivated(self):
        # logic

    @PostCreateEvent()
    def post_create(self):
        # logic.. end docs include.. |latest-version| image::https://img.shields.io/badge/version-1.1-green:alt: Latest version on PyPI
:target:https://pypi.org/project/django-model-event-actions/.. |python-support| image::https://img.shields.io/badge/python-%2B3.6-blue:target:https://pypi.org/project/django-model-event-actions/:alt: Python version
.. |django-support| image::https://img.shields.io/badge/django-%2B2.1-blue:target:https://pypi.org/project/django-model-event-actions/:alt: Django versions
.. |pypi| image::https://img.shields.io/badge/pypi-1.1-blue:target:https://pypi.org/project/django-model-event-actions/:alt: Pypi link
.. |license| image::https://img.shields.io/badge/license-MIT-green:alt: Software license
:target:https://github.com/aryabartar/django-model-event-actions/blob/master/LICENSE.. _Django:http://www.djangoproject.com/Installation
++++++++++++.. start installation includeGet the package from pypi::$ pip install django-model-event-actionsSubclass the models:.. code-block:: pythonfrom django_model_event_actions.models import EventActionModel

class MyClass(EventActionModel):
    ...Add the event decorator:.. code-block:: pythonfrom django_model_event_actions.models import EventActionModel

class MyClass(EventActionModel):
    name = models.CharField()

    @PostCreateEvent(field='name'):
    def my_handler(self):
        # logic.. end installation includeTutorial
++++++++To start using the package take a look at the documentation_ in readthedocs... _documentation:http://www.djangoproject.com/
Package: django-modelfeedback
Adds support for receive feedback to django models using Likert scale.Detailed documentation is inModel Feedback Github Page.Intallationpipinstalldjango-modelfeedbackQuick startAdd “modelfeedback” to your INSTALLED_APPS setting like this:INSTALLED_APPS = (
    ...
    'modelfeedback',
)Include the modelfeedback URLconf in your project urls.py like this:url(r'^feedback/', include('modelfeedback.urls')),Runpython manage.py syncdbto create the feedback models.Sample Applicationcdsamplepipinstall-rrequirements.txt./managesyncdb./managerunserverVisithttp://127.0.0.1:8000/to see the sample.Or visit thelive demo.LicenseMIT License. See LICENSE file.
Package: django-model-field-meta
django-model-field-metaAn easy-to-use plugin to allow optional metadata of model fields.Compatible withdjango-model-utils,safedelete, etc.Tested on Python 3+, Django 2.1+.ExampleInserting metadata:fromdjango.dbimportmodels# Remove thisfrommodel_field_metaimportmodels,FieldMetaMixinclassMyModel(FieldMetaMixin,models.Model):# Add FieldMetaMixinmy_field=models.TextField(meta={"key":"value"})Accessing metadata:model_obj=MyModel.objects.first()model_obj.get_field_meta("my_field")# {"key": "value"}Or,MyModel.get_field_meta("my_field")# {"key": "value"}InstallationInstall from PiPy:pipinstalldjango-model-field-metaor, if you are using Pipenv:pipenvinstalldjango-model-field-metaWhy metadata in model field?In one of my Django projects, I needed to supply extra information about our model fields.For my purpose,help_textis too limited. Using code comments is not feasible as I need to use those information programatically.Hence,django_model_field_metapackage is created.Compatibility with third-party packagesIn my project, I use:django-model-utilsfor itsInheritanceManager.safedeletefor itsSafeDeleteModelSo far, I haven't encounter any issue. Feel free to report if you do.IssuesIf you have questions or issues using it, please create a Github issue at:https://github.com/melvinkcx/django-model-field-meta/issues
Package: django-model-filters
NOTE: This app has changed its name to django-model-blocks.  The Source is available athttps://github.com/mjumbewu/django-model-blocksand the package is athttp://pypi.python.org/pypi/django-model-blocks/.Please update your requirements files accordingly.  Thank you.Themodel_filtersapp provides you with automatically generated, stylable
generic Django model template partials.