Saravanan666/pypi-org huggingface dataset:
Package: djangomockingbird
Django Mockingbird: the fastest way to write the fastest Django unit tests1. What is Django Mockingbird and why would I need it?Until now, there were two options for writing tests for a Django application: either create objects in the database for every test or mock the database queries usingUnit test’s Mock. While the former is slow, the latter is complicated to write and read. Both add a lot of setup code to our tests. Django Mockingbird introduces a new way to write tests for Django, which is fast to run as well as simple to write.2. How does it work?It works by creating a mock object which behaves exactly like the Django model, but does not execute any queries under the hood. It only takes one line of code to use it in your test. It is not meant to be used in place of frameworks likePytest, but to complement them.3. How do I use it?InstallationpipinstalldjangomockingbirdUsagefromdjangomockingbirdimportmock_model@mock_model('myapp.myfile.MyModel')deftest_my_test():some_test_query=MyModel.objects.filter(bar='bar').filter.(foo='foo').first()#some more code#assertions hereWith the mock_model decorator this test will pass no matter how complicated the query and will never touch the database.Specifiying mock return dataYou can specify the values of specific fields of the model object you are mocking. If you don’t empty strings will be returned. Construct a dictionary with field names as keys and desired returs as values and pass it to the 'specs' argument of make_mocks. If you try to specify a nonexisant field as a key an error will be thrown, but you can specify any kind of value you want.@mock_model('myapp.myfile.MyModel',specs={'field':'value'})Attention! Cases where returns must be specified: Model methodsIf your model has custom methods and they are used by the test, you must specify their names and return data to the mock, otherwise your tests won't pass.model_method_specs={'to_dict':{'':''}}@mock_model('myapp.myfile.MyModel',model_method_specs=model_method_specs)4. Is it production ready? Can I help make it better?This is still a very new project, but is quite stable for the general use case. However, there are advanced use cases that are not yet supported, most notablycustom model managers. For those test cases you can try supplementing Django Mockingbird with your own code or other libraries. Because this tool is really just one elaborate mock model it is very flexible and plays well with pretty much anything.We would appreciate you opening issues to bring any defects or oversights to light. Contributions are also kindly accepted - see more on the code arhitecture principles below if you are interested.5. Where can I read more details on the architecture?Read about the how functional programming principles were used in the libraryhereand on metaprogramming featureshere.
Package: django-mock-rest
Django mock restSimple way to create static mock data at rest api endpoints in the Django admin.If you’re designing a rest api client, and want to create a simple mock server for testing, then this app lets you do that using the Django admin.InstallInstall usingpipinstalldjango-mock-restAdddjango_mock_restto installed apps insettings.py:INSTALLED_APPS=[...'django_mock_rest',...]By default the mock service is available only inDEBUGmode. You can override this withDJANGO_MOCK_REST = TrueorFalse.Add the root url tourl.py:urlpatterns=[...url(r'^api-mock/',include('django_mock_rest.urls')),...]How to useIn the Django admin, you can create endpoints:After that, you can do http(s) request to the endpoints you defined:$curl-XGEThttp://127.0.0.1:8000/api-mock/post/1/{"post":"Hello world"}You can also see an overview of all the mock endpoints (if logged in) by visiting~, i.e.http://127.0.0.1:8000/api-mock/~.
Package: django-modal-2fa
Installationsettingsfrom modal_2fa.settings_helper import modal_2fa_apps_admin
INSTALLED_APPS += [
    *modal_2fa_apps_admin,
]

OTP_TOTP_ISSUER = '**appname**'
AUTHENTICATION_BACKENDS = ['modal_2fa.auth.CookieBackend']        
LOGIN_URL ='/auth/login/'
LOGOUT_REDIRECT_URL = '/auth/login'remove'django.contrib.auth'from INSTALLED_APPSurlsfrom modal_2fa.utils import get_custom_auth

urlpatterns += [
    path('', include(get_custom_auth().paths(include_admin=True))),    
]
Package: django-model2puml
django-model2puml app is a generator of project models structure in
PlantUML class notation.Quick startAdd “uml_generator” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'puml_generator',
    ...
]Run django management commandgenerate_pumllike this./manage.py generate_pumlParams:--file - output file
--title - provide a title for diagram
--title-font-size - provide a custom title font size (default is 72)
--add-help - add models docstrings to diagram
--add-choices - add Choices description of fields to diagram
--add-legend - include explanation of the symbols used
--add-omitted-headers - add a header stub for omitted foreign app
--omit-history - omit Historical* tables from django-simple-history
--omit - specify apps to be omitted in diagram
--include - specify apps to be included in diagram; other will be omitted
--headers-only - use only model header and relations, omit fields list
--url - generate URL to plantuml.com/plantuml/svg/YOUR_DIAGRAMCheck generated PlantUML file!./manage.py generate_puml--filediagram.puml--includeauth contenttypes--add-help--add-legendRelease notesv0.4.1 (2023-02-13)Fix usage of empty title not to break output filenamev0.4.0 (2023-02-11)Add title-font-size paramv0.3.0 (2023-02-11)Add URL to plantuml.com generationv0.2.1 (2022-06-05)Refine README.rstv0.2.0 (2022-04-17)Add omit-history flag for omitdjango-simple-historylibrary modelsv0.1.14 (2021-03-15)Fix ImportError in utils.pyv0.1.13 (2020-10-17)Add documentation to generatorLimit docstrings lengthFix choices generation issuesv0.1.12 (2020-10-15)Use UTF-8 for saving outputv0.1.11 (2020-10-15)Add headers-only flag to use only model header and relations, omit fields list in UMLReleases earlier than v0.1.11 yanked due to significant settings issues and must not be used
Package: django-modeladmin
Installation$pipinstalldjango-modeladminProsautolist_display(all fields)autolist_filter(BooleanFieldfields)autosearch_fields(CharFieldandTextFieldfields)list_displayformatters -elapsed,strftime,timesinceExamplesadmin.pyfromdjango_modeladminimportadminfrom.modelsimportMyModelAdmin@admin.register(Author)classMyModelAdmin(admin.ModelAdmin):...list_displayformatters:list_display=['id','started_at',('strftime','started_at','%H-%M-%S','started',),('elapsed','started_at','finished_at','elapsed',),('timesince','created_at','',),]
Package: django-model-admin-autocomplete
This simple django app enables users to do a few tweaks toDjango’s built-in autocompletefeature.Installationpip install django-model-admin-autocompleteand then add this to yoursettings.pymoduleSILENCED_SYSTEM_CHECKS = ['admin.E039', 'admin.E040']UsageConsider you have a few models as,# models.pyclassArticle(models.Model):headline=models.CharField(max_length=100)pub_date=models.DateField()publications=models.ManyToManyField(Publication)reporter=models.ForeignKey(Reporter,on_delete=models.CASCADE)def__str__(self):returnself.headlineand you need autocomplete fields forpublicationsandreporterin models admin.# admin.pyfromdjango.contribimportadminfrom.modelsimportArticlefrommodel_admin_autocompleteimportModelAdminAutoCompleteclassArticleModelAdmin(ModelAdminAutoComplete,admin.ModelAdmin):autocomplete_fields=('publications','reporter')admin.site.register(Article,ArticleModelAdmin)DemoIf you want to see a very simple Django demo project using this module, please take a look atmodel-admin-autocomplete-demo.
Package: django-model-admin-fields
Django Model Admin FieldsDjangois one of the most popular Python web frameworks today. Importantly, it provides anORMpermitting us to define models as Python classes that Django maps to a database representations for us.A very common, nearly ubiquitous desire/need I have is to keep some record against all database objects as to who created them, when and who last edited them and when. Very basic tracking fields. Given the ubiquity of the need it was best implemented as an abstract model that my models derive from.The basic Django example of model:fromdjango.dbimportmodelsclassPerson(models.Model):first_name=models.CharField(max_length=30)last_name=models.CharField(max_length=30)can be extended thusly:fromdjango.dbimportmodelsfromdjango_model_admin_fieldsimportAdminModelclassPerson(AdminModel):first_name=models.CharField(max_length=30)last_name=models.CharField(max_length=30)which has the simple effect of adding the following fields to the model silently:created_by=models.ForeignKey(User,verbose_name='Created By',related_name='%(class)ss_created',editable=False,null=True,on_delete=models.SET_NULL)created_on=models.DateTimeField('Time of Creation',editable=False,null=True)created_on_tz=TimeZoneField('Time of Creation, Timezone',default=settings.TIME_ZONE,editable=False)last_edited_by=models.ForeignKey(User,verbose_name='Last Edited By',related_name='%(class)ss_last_edited',editable=False,null=True,on_delete=models.SET_NULL)last_edited_on=models.DateTimeField('Time of Last Edit',editable=False,null=True)last_edited_on_tz=TimeZoneField('Time of Last Edit, Timezone',default=settings.TIME_ZONE,editable=False)(a more precise description of course is in__init__.py)Importantly it also overrides the model'ssave()method to set those six fields before callingsuper().save()(i.e. the default save method) and thus these fields are automatically managed.Thecurrently activeDjango timezone is saved as well to support sensible human interpretation of the saved times (as Django'sDateTimeField) is not timezone aware.To make use of that easier, two properties are also added to the model:created_on_localandlast_edited_on_localwhich are timezone aware versions of the naivecreated_oneandlast_edited_onfields.To illustrate use of the Person example above:person=Person()person.first_name="John"person.last_name="Smith"person.saveprint(f"{person.first_name}{person.last_name}")print(f"was created by{person.created_by}on{person.created_on_local}.")Of course to make use of local times, you need to activate the timezone that the creating user is in. To do that you need to know it first. The JavaScript libraryjstzis useful in that regard for detecting the users timezone and there's a great guide onsetting timezonesin Django in the Django documentation proper.
Package: django-model-admin-helper
Django Model Admin HelpersLink to repository:https://github.com/Arpaso/django-model-admin-helperProvides classes to extend default django admin functionality:ButtonableModelAdminModelAdminWithForeignKeyLinksMetaclass- adds clickable foreign key      links at admin interface in list view; Useslist_displayfields to try adding link to the field in list item.AdminURLMixin- provides ability to extend /admin/ urls and make views to urls like: /admin/myurl.Usageadmin.py:from admin_helpers import ButtonableModelAdmin, AdminURLMixin, ModelAdminWithForeignKeyLinksMetaclass

class MyModelAdmin(AdminURLMixin, ButtonableModelAdmin):
    __metaclass__ = ModelAdminWithForeignKeyLinksMetaclass

    list_display = ('title', 'link_to_user') # user is a foreignkey field of the MyModel

    def get_urls(self):
        urls = super(MyModelAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^my_view/$', self.my_view)
        )
        return my_urls + urls

    def my_view(self, request):
        # custom view which should return an HttpResponse
        passNote:
Notice that the custom patterns are included before the regular admin URLs: the admin URL patterns are very permissive and will match nearly anything, so you’ll usually want to prepend your custom URLs to the built-in ones.
In this example, my_view will be accessed at /admin/myapp/mymodel/my_view/ (assuming the admin URLs are included at /admin/.)Written by the development team of Arpaso company:http://arpaso.com
Package: django-modeladmin-reorder
Custom ordering for the apps and models in the admin app. You can also rename, cross link or exclude models from the app list.FeaturesReorder apps in admin index - this will allow you to position most used apps in top of the page, instead of listing apps alphabetically. e.g.sitesapp before theauthappRename app labels easily for third party apps without having to modify the source code. e.g. renameauthapp toAuthorisationfor the django admin app.Split large apps into smaller groups of models.Reorder models within an app. e.g.auth.Usermodel before theauth.Groupmodel.Exclude any of the models from the app list. e.g. Excludeauth.Groupfrom the app list. Please note this only excludes the model from the app list and it doesn’t protect it from access via url.Cross link models from multiple apps. e.g. Addsites.Sitemodel to theauthapp.Rename individual models in the app list. e.g. renameauth.UserfromUsertoStaffDocumentationThe full documentation is athttps://django-modeladmin-reorder.readthedocs.org.InstallInstall django-modeladmin-reorder:pipinstalldjango-modeladmin-reorderConfigurationAddadmin_reordertoINSTALLED_APPS:INSTALLED_APPS=(...'admin_reorder',...)Add theModelAdminReordertoMIDDLEWARE_CLASSES:MIDDLEWARE_CLASSES=(...'admin_reorder.middleware.ModelAdminReorder',...)Add the settingADMIN_REORDERto your settings.py:ADMIN_REORDER=(# Keep original label and models'sites',# Rename app{'app':'auth','label':'Authorisation'},# Reorder app models{'app':'auth','models':('auth.User','auth.Group')},# Exclude models{'app':'auth','models':('auth.User',)},# Cross-linked models{'app':'auth','models':('auth.User','sites.Site')},# models with custom name{'app':'auth','models':('auth.Group',{'model':'auth.User','label':'Staff'},)},)History0.1.0 (2014-08-01)First release on PyPI.
Package: django-modeladmin-reorder-reborn
django-modeladmin-reorder-rebornReviving the old Djangodjango-modeladmin-reorderpackage.Detaches model groups from the apps, granting the flexibility to organize models
into various groups, change models and groups order.
Custom names can be assigned to groups.Implemented origin featuresReorder apps in admin index - this will allow you to position most used apps in top of the page, instead of listing apps alphabetically. e.g. sites app before the auth appRename app labels easily for third party apps without having to modify the source code. e.g. rename auth app to Authorisation for the django admin app.Split large apps into smaller groups of models.Reorder models within an group. e.g. auth.User model before the auth.Group model.Exclude any of the models from the app list. e.g. Exclude auth.Group from the app list. Please note this only excludes the model from the app list and it doesn't protect it from access via url.Not implemented featuresCross link models from multiple apps. e.g. Add sites.Site model to the auth app.Rename individual models in the app list. e.g. rename auth.User from User to StaffNew featuresGathering models of the app that haven't been included in other groups.RequirementsPython >= 3.5Django >= 4.1InstallInstall django-modeladmin-reorder-reborn:pip install django-modeladmin-reorder-rebornConfigurationCreateadmin_apps.pyfile in your project folder:fromdjango.contrib.admin.appsimportAdminConfigclassMyAdminConfig(AdminConfig):default_site="admin_reorder.ReorderingAdminSite"Replacedjango.contrib.admintoproject.admin_apps.MyAdminConfigin your settings.py:INSTALLED_APPS=(...'̶d̶j̶a̶n̶g̶o̶.̶c̶o̶n̶t̶r̶i̶b̶.̶a̶d̶m̶i̶n','your_project_name.admin_apps.MyAdminConfig',...)Add the setting ADMIN_REORDER to your settings.py:ADMIN_REORDER=[# Keep original label and models, but change group order{'app':'sites'},# Rename app{'app':'auth','label':'Authorisation'},# Reorder app models{'app':'auth','models':('User','Group')},# Exclude models{'app':'auth','models':('User',)},# Gather not included in any group models{'app':'auth','models':'__rest__'},]
Package: django-model-api
# django-easy-apiNow there is no need to create apis for common CRUD operation for any model.
By usingdjango-easy-apiits really easy. Kindly follow the below steps for including this library into your project.Create Your django project.Addeasy_apiin settings.pyINSTALLED_APPS = [
.
.
.
‘easy_api’
]Create your django appNow in models.py follow create your model by inheriting EasyAPI model from easy_api app.from django.db import models
from easy_api.models import EasyAPIclass MyModel(EasyAPI):# Your Requried field here.Migrate your models.This is the last step. You need to add this model in your app’s urls.pyfrom django.urls import path
from .models import MyModelurlpatterns = [path(‘myurl/’, MyModel.as_view()),]7. That’s it. Now you will have common GET/POST/PUT/DELETE methods on your model.
Also you can attach query_params only foridin your url.
For example:http://localhost:8000/myurl/?id=18. You can also override get, post, put and delete method according to your need.
For example:from django.db import models
from easy_api.models import EasyAPIclass MyModel(EasyAPI):# Your Requried field here.def get(self, request):#Your logic
Package: django-modelapiview
Django_APIViewImplement a base generic view for handling model RESTful endpointsUsage# models.pyfromdjango.dbimportmodelsfromdjango_modelapiviewimportJSONMixinclassMyModel(JSONMixin,models.Model):"""Declare your model as you usually do butadd a json_fields list"""json_fields:list[str]=['text','image','fk','fk_reverse','m2m','my_method']text=models.TextField()image=models.ImageField()fk=models.ForeignKey(...)# fk_reversem2m=models.ManyToManyField(...)defmy_method(self):return"my custom value"# views.pyfromdjango_modelapiviewimportAPIViewfromdjango_modelapiview.responsesimportAPIResponsefrom.modelsimportMyModelclassMyView(APIView):# Requiredroute:str="myroute"# The url to access your view# Optionalenforce_authentification:bool=True# Should this model be restricted with Token accessdefget(self,request,*args,**kwargs)->APIResponse:...# One of head, options, get...# views.pyfromdjango_modelapiviewimportModelAPIViewfrom.modelsimportMyModelclassMyModelView(ModelAPIView):# Requiredmodel:JSONMixin=MyModel# Your modelroute:str="mymodels"# The url to access your collection# Optionalqueryset:QuerySet=MyModel.objects.all()# A custom base queryset (will be affected by query filters)singular_name:str="my model"# Singular name of your model for reason messageplural_name:str="my models"# Plural name of your model for reason messageenforce_authentification:bool=True# Should this model be restricted with Token accessquery_parameters:list[tuple[str,Callable[[QuerySet,object],QuerySet]]]=[('order_by',lambdaqueryset,field_names:queryset.order_by(*field_names.split(","))iffield_nameselsequeryset),('limit',lambdaqueryset,limit:queryset[:int(limit)]iflimitelsequeryset),# Should be last since sliced QuerySet can't be filtered anymore]defget(self,request,*args,**kwargs)->APIResponse:...# One of head, options, get...# urls.pyfromdjango.urlsimportpath,includefrom.importviewsurlpatterns=[path("",include("django_routeview")),# Django RouteView are used as based class for APIView in order to automatically register them]# You can use query parameters like order_by or limit (or customs):https://myhost.com/api/mymodel/?order_by=-id&limit=1# Will inverse order by id and limit to one : get the last id# Or you can use Django defined filters:https://myhost.com/api/mymodel/?id__in=1,2,3&foreignkey__id__in=2,3&field__lte=5# And finally both:https://myhost.com/api/mymodel/?manytomany__in=2,3&field__lte=5&limit=10It also supports translation:First enable it as an app#settings.pyINSTALLED_APPS=[...'django_modelapiview',...]Then change the language using GET parameters:#Currently supports : enlish(en)(default), français(fr)https://myhost.com/api/mymodel/?lang=frUsing base viewsDjango ModelAPIView provides 2 base views:LoginView: to handle authentification (using the default Django authentification system)URLsView: to list the urls availablesUsage# urls.pyfromdjango.urlsimportpathfromdjango_modelapiview.viewsimportLoginView,URLsView# Importing them is enoughErrorsIf you get a "Verb not implemented" reason from your endpoint but you are sure to have defined it.
You probable just forgot the-> APIResponsereturn type hint.
Package: django-model-audit
Audit trail is a simple Django app to track the database changes and maintain history in any application. It also provide history for many_to_many fields, with ready admin page.Quick startInstall django-model-audit:pip install django-model-auditAdd “audit_trail” to your INSTALLED_APPS:INSTALLED_APPS = [
        ...
       'audit_trail',
]Add Middlewre:MIDDLEWARE = [
       ...
       'audit_trail.middleware.AuditMiddleware'
]Run Migrate:python manage.py migrateAdd an AuditTrail and manager to model you want to create history:from audit_trail.history import AuditTrail, AuditManager
class MyModel(models.Model):
    ...

    history = AuditTrail()

    objects = AuditManager.as_manager()

    class Meta:
        display_format = '{model_name.field_name}'To add admin screen for audit simply inherit AuditTrailAdmin in your model admin:from audit_trail.admin import AuditTrailAdmin
class MyModelAdmin(AuditTrailAdmin):
    ...Visit django model admin screen to get the history of particular
model(Click on History button in that screen).To get audit trail of many_to_many fields just send signal from your AppConfig class’ ready method:from audit_trail.signals import audit_m2m_ready

class MyappConfig(AppConfig):
    ...
    def ready(self):
        audit_m2m.ready.send(sender=self.__class__)
        ...To get audit trail logs in your django app import and call function
get_audit_trail() like this:from audit_trail.admin import get_audit_trail
get_audit_trail(model_name, object_id)
Package: django-model-audit-history
# django-model-audit-historyProvides an `AuditHistory` model field to store a chronological record of changes to a model (“audit history”) on the model. The historical record is stored in a designated JSON field, so no additional database tables are required.Supports Django 1.11 (and possibly Django 2.x in the future) and PostgreSQL database backends.## CI[![Build Status](https://travis-ci.org/nexto/django-model-audit-history.svg?branch=master)](https://travis-ci.org/nexto/django-model-audit-history)## UsageThe basic principles are as follows:1. To enable this for a model, you have to make these changes:* add an `AuditHistoryField` named `history` to the model* add the `AuditHistoryMixin` to the model class* create ModelAdmin:```ModelAdmin(AuditHistoryAdminMixin, admin.ModelAdmin):pass```* add your ModelAdmin to admin site `admin.site.register(model, ModelAdmin)`2. Then, instead of calling regular `save()` on the model after changing it, call `save_with_audit_record()` instead (passing in some meta data you want saved alongside, e.g. the `event` that caused the change, the `user` triggering it and some `payload` usually the set of modified fields.3. The history will appear in human-readable form in the admin.That’s pretty much all there is to it.## Testapp setup and first steps1. Install Postgres locally (e.g. 10.x)2. Create local database `audithistory`, owned by user `dev`3. Create a virtualenv and activate: `virtualenv venv`, then `source venv/bin/activate`4. Install dependencies into virtualenv: `pip install --requirement requirements.txt`5. Run `manage.py migrate`6. Run `manage.py createsuperuser`7. Run `manage.py runserver`8. Create new model on http://localhost:8000/admin/test_app/blogpost/9. Edit model via http://localhost:8000/edit/1/10. Reload admin page and inspect history record## Run tests in local environment:* Run `manage.py test` (Ensure that user dev has rights to db creation `alter user dev createdb;`)
Package: django-model-auditmatic
this probably doesn’t work well yet.UsageAdd django_auditmatic to INSTALLED_APPS.Example:INSTALLED_APPS.append("django_auditmatic")Configure which models you want to audit in settings.pyExample:AUDITMATIC = {
    "apps": {
        "auth": {
            "User": {"m2m": any},
        }
    }
}In this example will only include the User model from the auth app, along with any many-to-many relationships.Then run:python manage.py install_audit