Saravanan666/pypi-org huggingface dataset:
Package: django-reinhardt
django-reinhardtThere are many object permission backends likedjango-guardianordjango-permission.But some time, it is needed to define permissions as not just object-user relationship.django-reinhardtmake you handle object permissions by defining methods in your django modelFree software: MIT licenseDocumentation:https://django-reinhardt.readthedocs.io.InstallationUsepiplike:$ pip install django-reinhardtUsageAdd extra authorization backends in your settings.py:AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', # default
    'reinhardt.backends.PermissionBackend',
)It’s done. you don’t need to add any app or migrate anything.Assume thatInquirymodel needs to have two permission:change_inqury,view_inquiryclass Inquiry(models.Model):

    writer = models.ForeignKey(settings.AUTH_USER_MODEL)
    text = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

    @object_permission(codename='change_inquiry')
    def is_changeable_by(self, user):
        return self.writer == user or user.is_staff

    @object_permission(codename='view_inquiry')
    def is_viewable_by(self, user):
        return self.writer == userThen you can just define methods havinguserparameter, decorated byobject_permission.Now the following codes will work as expected:user1 = get_user_model().objects.create(
    username='nanase'
)
user2 = get_user_model().objects.create(
    username='maiyan'
)
user3 = get_user_model().objects.create(
    username='ikuta'
)
inquiry = Inquiry.objects.create(
    writer=self.user1,
    text='How can I delete my account?'
)

assert user1.has_perm('yourapp.change_inquiry', obj=inquiry) == True
assert user2.has_perm('yourapp.view_inquiry', obj=inquiry) == False
assert user3.has_perm('yourapp.change_inquiry', obj=inquiry) == False
assert user3.has_perm('yourapp.view_inquiry', obj=inquiry) == TrueCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.0 (2016-08-2)Change the way how to distinguish permission-related method from others.Now you should useobject_permissiondecorator instead ofcan_prefix to define permission methods.0.1.0 (2016-07-19)First release on PyPI.
Package: django-reinstallation-app
Скрипт для:Переустановки бд, задействованных в джанго-проекте.Удаления всех старых файлов миграций, создания и применения новых для всех приложений в джанго-проекте.УстановкаУстановить пакет:pip install django-reinstallation-appИли, находясь внутриdatabase_installer:pip install dist/django_reinstallation_app-X.tar.gzДобавитьdjango_reinstallation_appвsettings.INSTALLED_APPS:INSTALLED_APPS=(...'django_reinstallation_app',...)НастройкаСкрипт по умолчанию берет все бд и их настройки (name, user, host ...) изsettings.DATABASES. БД должна бытьpostgres.
Заигнорить бд, для которой переустановку делать не надо можно, указав вsettings.pyDATABASES_TO_IGNORE=['*']# Заигнорить все бд, которые есть в проектеDATABASES_TO_IGNORE=['some_db']# Заигнорить бд some_db (some_db - имя бд в postgres)Скрипт по умолчанию удаляет старые миграции, создает новые и применяет их для всех приложений, созданных пользователем вsettings.INSTALLED_APPSЗаигнорить приложение, для которого не нужно этого делать можно, указав вsettings.pyDJANGO_APPS_TO_IGNORE=['*']# Заигнорить все приложения, которые есть в проектеDJANGO_APPS_TO_IGNORE=['app']# Заигнорить приложение appЗапускЗапуск скрипта реализован как джанго-коммандаpython manage.py install -p -m-p- переустановка БД-m- удаление старых миграция, создание и примение новых
Package: django-related-admin
Allow foreign key attributes in Django admin change listlist_displaywith ‘__’This is based onDjangoSnippet 2996which was made by Kpacn.InstallationThis library is on PyPI so you can install it with:pip install django-related-adminor from github:pip install git+https://github.com/PetrDlouhy/django-related-admin#egg=django-related-adminAdd “related_admin” to your INSTALLED_APPS setting like this:INSTALLED_APPS = (
    ...
    'related_admin',
    'django.contrib.admin',
)Note: Django-related-admin changeschange_list.htmltemplate to disablewhite-space:nowrap;css class on admin headers to allow long (posibly related) header names to wrap.
If you want this behaviour, add the app beforedjango.contrib.admin, otherwise after.UsageJust use it instead of model.Admin:from related_admin import RelatedFieldAdmin
from related_admin import getter_for_related_field

class FooAdmin(RelatedFieldAdmin):
    # these fields will work automatically (and boolean fields will display an icon):
    list_display = ('address__phone','address__country__country_code','address__foo')

    # ... but you can also define them manually if you need to override short_description or boolean parameter:
    address__foo = getter_for_related_field('address__foo', short_description='Custom Name', boolean=True)
Package: django-relatedadminwidget
Widget for displaying edit and delete links alongside foreign key admin widgets![Flowers](https://github.com/benjaoming/django-relatedadminwidget/raw/master/screenshot.png)Also see this project: [django-admin-enhancer](https://github.com/charettes/django-admin-enhancer)Installation:pip install django-relatedadminwidgetAdd “relatedwidget” to settings.INSTALLED_APPSYou may want to run your project’s ./manage.py collectstaticIn your applications’ admin.py, let the model admins inherit from RelatedWidgetWrapperBase like in this example:from django.contrib import admin
from relatedwidget import RelatedWidgetWrapperBaseclass MyModelAdmin(RelatedWidgetWrapperBase, admin.ModelAdmin):passadmin.site.register(MyModel, MyModelAdmin)It also works with TabularInline and StackedInline! Remember the order of inheritence, always put RelatedWidgetWrapperBase first!TroubleshootingIf you get aTemplateDoesNotExisterror on ‘relatedwidget/widget.html’, you might have to adddjango.template.loaders.eggs.Loaderto yoursettings.TEMPLATE_LOADERS.CreditsUser [nasp](http://djangosnippets.org/users/nasp/) did most of the work, I just updated it for Django 1.4 and packed it as an app.
Package: django-related-models
A library designed such that, when provided with a model instance it will return a QuerySet for the rows that are
associated with that model instance. It also works well withGenericForeignKeyobjects.>>>eminem=Artist.objects.filter(stage_name='Eminem').first()>>>list(get_related_objects(eminem))[<Albums:Kamikaze>,<Awards:Grammy>,<Cars:AudiR8Spyder>]>>>get_related_objects_mapping(eminem){<django.db.models.fields.related.ForeignKey:artist>:set([<Albums:Kamikaze>]),<django.db.models.fields.related.ForeignKey:artist>:set([<Awards:grammy>]),<django.contrib.contenttypes.fields.GenericForeignKeyobjectat0x106ff1f50>:set([<Cars:AudiR8Spyder>])}Installationpip install django-related-modelsDocumentationhttps://django-related-models.readthedocs.io/DevelopmentThe tests are run viatox, which you would need to install (if you don’t already have it).To get tox just:pip install toxTo run the all tests run:toxChangelog0.1.1 (2020-05-01)Updated tests for latest versions of Django and Python.0.1.0 (2018-08-28)First release on PyPI.
Package: django-relations
django-relationsInstallation# with pip

pip install django-relations# with pipenv

pipenv install django-relationsUsingfrom django_relations import AbstractDefaultClass

class MyModel(AbstractDefaultClass):
    field1 = models.OneToOneField(Model1, ...)
    field2 = models.ForeignKey(Model2, ...)
    field3 = models.ManyToManyField(Model3, ...)DescriptionBoost your Django app's speed with the all-new django-relations package. Say goodbye to manual query optimization – this package automatically detects relation fields and seamlessly integrates them into select_related and prefetch_related methods. 🚀 Supercharge response times, enhance UX, and free up your creative genius. Embrace efficiency and let django-relations handle the heavy lifting. Your queries, elevated.
Package: django-relationships
Descriptive relationships between auth.users:In [4]: john.relationships.friends()
Out[4]: [<User: Yoko>]

In [5]: john.relationships.following()
Out[5]: [<User: Paul>, <User: Yoko>]

In [6]: john.relationships.followers()
Out[6]: [<User: Yoko>]

In [7]: john.relationships.blockers()
Out[7]: [<User: Paul>]

In [8]: paul.relationships.blocking()
Out[8]: [<User: John>]You can create as many types of relationships as you like, or just use the
default ones, ‘following’ and ‘blocking’.From, To and SymmetricalRelationship types define each of the following cases:from - ‘following’, whoIam followingto - ‘followers’, who is followingmesymmetrical - ‘friends’,wefollow eachotherRelationship types can belogin_required, orprivate, and if you want
to make a relationship type unviewable (i.e. you may not want to allow
users to see who is blocking them), simply give it a unmatchable slug,
like ‘!blockers’.Admin InterfaceRelationships hook right into the pre-existing User admin, and appear below
the ‘Groups’ inline.Installationpython setup.py installORput therelationshipsfolder on your python-path
Package: django-relativedeltastore
django-relativedeltastoreA Django model field to storedateutil.relativedelta.relativedelta.The field is a subclass ofJSONFieldand simply stores the kwargs of arelativedeltainstance.The field is mainly meant to storerelativedelta.
The packagedjango-relativedeltaprovides better query support
(for relative units since it uses a sqlINTERVAL).The basic arguments for relative and absolute units are supported (year,years…microseconds).
Currently not supported are:weekday,leapdays,yearday&nlyeardayThe package also provides a form field to edit the value ofRelativeDeltaStoreFieldwith a custom
serialization format (configurable):1hour +1days -1seconds
Package: django-relatives
Utilities for linking to related objects in Django adminThis app requires Django 3.2 or greater and Python 3.8 or greater.Getting HelpDocumentation for django-relatives is available athttps://django-relatives.readthedocs.org/This app is available onPyPI.Submit issues on Github:https://github.com/treyhunner/django-relatives/issuesPull requests are welcome.  Read the CONTRIBUTING file for tips on submitting
a pull request.ScreenshotsRelated ProjectsThanks to the community for inspiration:linked readonly foreign key code snippetdjango-inlawsvariousStackOverflow answersabout related object links in admin
Package: django-relative-softdeletion
==================Django Relative SoftDeletion==================Django Relative SoftDeletion is a custom made Django plugin which allows you to Soft Delete database values, which means while deleting any data, it will flag the data as deleted but will not remove the data completely from database. And at the time of fetching data from database, you will automatically get filtered result (excluding deleted values).Another important implementation in this plugin is that it will filter out deleted values also while filtering on reverse relations. It means while usingfilter()orexclude()function on Foreign fields (reverse relation lookups also), it will not include the deleted data in the result.
If you want to include deleted data in filteration process, useall_objects()function instead ofobjects().InstallingActivate your environment and install the plugin using the command given below:pip install django-relative-softdeletionUsageImport theSoftDeletionModelfromdjango_soft_deletion.modelsand inherit in your Model classes:For example,from django_soft_deletion.models import SoftDeletionModel

class Employee(SoftDeletionModel):
	passFunctionsModel.objects()...: Return result excluding deleted valuesModel.all_objects()...: Return result including deleted valuesdelete(): Soft delete the itemhard_delete(): Permanent delete the item
Package: django-release-tracker
Django Heroku Github SyncDjango app for syncing Heroku and Github releases.Version supportThis app support Django 3.2+ and Python 3.10+.BackgroundIf you deploy your application to Heroku, and you store your code in
Github, you can create automated Release notes in GH each time a release
is deployed to Heroku.This uses Github's "automatically generated release
notes"
feature.How it worksThe underlying principle is simple - it uses Github's REST API to create
a new repo release (with associated tag) for a specific commit as
identified by the Heroku API, using the Heroku release version number as
the tag.The app uses Heroku'sApp
Webhooksapi:releasewebhook, which receives updates each time a release is
created, or its status is updated. (The updates are important as a
release goes through various states, and is not released until the state
reachessucceeded). You can read more about the release webhook
payloadhere.ConfigurationDjangoAdd toINSTALLED_APPS...HerokuYou must create a new webhook subscription point at this app (wherever
you have it deployed).GithubYou don't need to do anything to configure Github, but you do need to
give access to the API.TestsRunning testsThe tests themselves usepytestas the test runner. If you have
installed thepoetryevironment, you can run them thus:$ poetry run pytestor$ poetry shell
(release_tracker) $ pytestThe full suite is controlled bytox, which contains a set of
environments that will format, lint, and test against all support PythonDjango version combinations.$ tox
...
______________________ summary __________________________
  fmt: commands succeeded
  lint: commands succeeded
  mypy: commands succeeded
  py37-django22: commands succeeded
  py37-django32: commands succeeded
  py37-djangomain: commands succeeded
  py38-django22: commands succeeded
  py38-django32: commands succeeded
  py38-djangomain: commands succeeded
  py39-django22: commands succeeded
  py39-django32: commands succeeded
  py39-djangomain: commands succeededCIThere is a.github/workflows/tox.ymlfile that can be used as a
baseline to run all of the tests on Github.Heroku
Package: django-relinking
#DJANGO-RELINKINGDjango-relinking application adds function and template filter for relinking custom text.Installation------------------------1. Run from command line "pip install django-relinking"2. Add "django_relinking" to INSTALLED_APPS in your settings package3. Run migrations: ``` python manage.py migrate django_relinking ```Options------------------------_If you want you can redefine next options:_+ __RELINKING_LINK_TEMPLATE__ - template for link tag.*Default*: ```RELINKING_LINK_TEMPLATE = '<a target="{target}" href="{url}">{text}</a>'```+ __RELINKING_ENABLE_CACHE__ - enable or disable caching.*Default*: ```RELINKING_ENABLE_CACHE = False```+ __RELINKING_CACHE_PREFIX__ - prefix for keys in cache.*Default*: ```RELINKING_CACHE_PREFIX = "{links_table}.{hash}"```+ __RELINKING_INDEX_PATTERN__ - temporary pattern for replacting keys to link indexes.*Default*: ```RELINKING_INDEX_PATTERN =  "<%=link {}=%>"```Usage------------------------*Before usage you must register models or other objects which have ```get_absolute_url``` method:*```pythonfrom django_relinking.content_types import register"""content_type - class of model or view which has method 'get_absolute_url`verbose_name - human title of content type.--- verbose_name can be a function. Default is None.--- If verbose_name is None and content_type has attribute 'verbose_name',------ then verbose_name = content_type.verbose_name--- If verbose_name is None and content_type has method 'verbose_name',------ then verbose_name = content_type.verbose_name()--- If verbose_name is None and content_type hasn't attribute 'verbose_name'------ then verbose_name = content_type.__name__objects - queryset or list of this content_type objects.--- For example: ``` Model.objects.all() ```.--- Every objects must have attribute pk and `get_absolute_url` method--- If objects is None - this content type is a single--- and it must have `get_absolute_url` method"""register(content_type, verbose_name, objects)```*Also you can:*```pythonfrom django_relinking.content_types import register_all, unregister, unregister_all## Register many content types for one timeregister_all(content_type1, content_type2, ..., content_typeN)## Unregister registered content typeunregister(content_type)## Unregister all registered content typesunregister_all()## Unregister some registered content typesunregister_all(content_type1, content_type2, ..., content_typeN)```____________________________________________________When you register appropriate content types you can:____________________________________________________**In template:**```html{% load relinking %}<!-- Plain text -->{% filter relink %}plain text{% endfilter %}<!-- variable -->{{ model.attr|relink }}```**In code:**```pythonfrom django_relinking import relink_textrelinked = relink_text(some_text_with_keywords)```
Package: django-remake-migrations
Django remake migrationsDocumentation:https://django-remake-migrations.readthedocs.ioSource Code:https://github.com/browniebroke/django-remake-migrationsA Django admin command to recreate all migrations in a project. Like asquashmigrationscommand on steroids.The problemThe built-insquashmigrationscommand is great, but it has some limitations:It only works on a single app at a time, which means that you need to run it for each app in your project. On a project with enough cross-apps dependencies, it quickly becomes impossible to run.It doesn't optimise the operations, it only reduces the number of migration files. That being said, Django 4.1 introduced a newoptimizemigrationscommandwhich sounds like it might be doing just this.This command aims at solving this problem, by recreating all the migration files in the whole project, from scratch, and mark them as applied by using thereplacesattribute.It makes an important trade-off though: it does NOT try to be correct when setting thereplacesattribute. The only guarantees are that:all old migrations are marked as replacedonce.all new migrations replace at least one of the old migrationsThis is OK to make this trade-off as long as all your environments are fully migrated when you deploy the remade migrations.Contributors ✨Thanks goes to these wonderful people (emoji key):Bruno Alla💻🤔📖Dmytro Litvinov📖This project follows theall-contributorsspecification. Contributions of any kind welcome!CreditsThis package was created withCopierand thebrowniebroke/pypackage-templateproject template.
Package: django-remdow
django-remdowSimple Django app for static files (img files):Download external imagesTo center imagesLazy load imagesInstallpipinstalldjango_remdowAdd'django_remdow',toINSTALLED_APPS:INSTALLED_APPS=[...'django_remdow',...]Usageremdow app contains different filters and tags. You can activate them with line in your template:# example.html{%loadremdow%}Download external imagesIf you have model with HTML content which contains external images, you can download external images to local folder and receive static with helpnginx:Use filterimg_local:{{'<img src="http://placehold.it/350x150"><img src="http://placehold.it/350x150">'|img_local}}This filter parse HTML code, findsimgtag, parses urls and then downloads image to local folder, and finally, replaces img url to local url.Lazy imagesYou can uselayzr.jsfor lazy loading images.Load lazy script:{%lazy_script_include%}And use filterimg_lazy:{{'<img src="http://placehold.it/350x150">'|img_lazy}}Center images withBootstrapFilterimg_centercenters all images{{'<img src="http://placehold.it/350x150">'|img_center}}Filter adds classcenter-blockto all img tagsImage responsive withBootstrapFilterimg-responsiveresponsives all images{{'<img src="http://placehold.it/350x150">'|img_responsive}}Filter adds classimg-responsiveto all img tags
Package: django-remote-auth-ldap
Django Remote Auth LDAP=========================[![Build Status](https://travis-ci.org/apmorton/django-remote-auth-ldap.png?branch=master)](https://travis-ci.org/apmorton/django-remote-auth-ldap)Purpose-------This app combines [django-auth-ldap](http://pythonhosted.org/django-auth-ldap/) with django's [RemoteUserBackend](https://docs.djangoproject.com/en/dev/howto/auth-remote-user/)It allows django applications hosted in IIS to take advantage of Windows Authentication in IIS (401 Challenge) while also having the advanced features offered in `django-auth-ldap`Features--------- [PEP 8](http://www.python.org/dev/peps/pep-0008/) compliance- [semver](http://semver.org/) complianceInstalling----------Install with pip/easy_install from the pypi`pip install django-remote-auth-ldap`or clone the latest sourcegit clone https://github.com/apmorton/django-remote-auth-ldap.gitcd django-remote-auth-ldappython setup.py installUsing-----In your django settings.py file configure django-auth-ldap normally, verify that the configuration is indeed working!Add the `RemoteUserMiddleware` class after the `AuthenticationMiddleware` class```pythonMIDDLEWARE_CLASSES = (...'django.contrib.auth.middleware.AuthenticationMiddleware','django_remote_auth_ldap.middleware.RemoteUserMiddleware',...)```Set the RemoteUserLDAPBackend as the authentication backend```pythonAUTHENTICATION_BACKENDS = ('django_remote_auth_ldap.backend.RemoteUserLDAPBackend',)```The application expects the remote user to be in the form `domain\user` (which is how IIS returns it)Settings--------There are a few settings you can use to control the behavior- `DRAL_CHECK_DOMAIN` - Boolean - whether or not to check the domain against a known list - default True- `DRAL_STRIP_DOMAIN` - Boolean - whether or not to strip the domain off the username before passing to django-auth-ldap - default True- `DRAL_DOMAINS` - List - list of domains to check against, should be lowercase! - default []- `DRAL_HEADER` - String - header to check for remote user in - default REMOTE_USER
Package: django-remote-image
=====Django-remote-image=====Django-remote-image is a Django app that adds a new form field for images.The default widget is a text input, that accepts a URL of a image.The image is downloaded and can be passed to a ``ImageField`` in a model. Pillow needs to be installed.It is possible to whitelist and blacklist file extensions.Examples are shown below.Quick start-----------$ pip install django-remote-imageUsing-----------Using the field in a form:.. code:: pythonimport remote_image import RemoteImageFieldclass ExampleForm(forms.Form):image = RemoteImageField()Whitelisting file extensions (only the ones in the list will be permitted):.. code:: pythonimport remote_image import RemoteImageFieldclass ExampleForm(forms.Form):image = RemoteImageField(ext_whitelist=['png', 'jpg'])Blacklisting file extensions (the ones in the list will be blocked):.. code:: pythonimport remote_image import RemoteImageFieldclass ExampleForm(forms.Form):image = RemoteImageField(ext_blacklist=['png', 'jpg'])