Saravanan666/pypi-org huggingface dataset:
Package: django-multi-action
Django Multi-action ViewOverviewThis tool can be used to route multiple actions to one endpoint in a Django projectInstallationInstall using pippipinstalldjango-multi-actionUsageCreate an action by inheritingBaseActionfrommultiactionimportBaseActionfromdjango.contrib.auth.modelsimportUserfromdjango.httpimportJsonResponseclassUserAction(BaseAction):defcreate_user(self,request,*args,**kwargs):username=request.GET.get('username')user=User.objects.create(username=username)returnJsonResponse(data={"id":user.id,"username":user.username},status=201)Create a connector that inheritBaseConnectorfrommultiactionimportBaseConnectorclassMyView(BaseConnector):actions={'user':UserAction}# urls.pyurlpatterns=[path('/actions',MyView.as_view())]Sample curl requestcurl--location--requestGET'http://127.0.0.1:8000/actions?action_id=user&target=create_user&username=sirrobot01'\When making a request toMyView, the following arerequiredaction_id: This is the action to be implementedtarget: This is the target/method to be implementedNote:Each target/method on the action class has two positional arguments,selfandrequestWhen making a GET request, your parameters will be accessible from request.GET, meanwhile,
it will be accessible from request.POST when making a POST requestIf you want to use django rest framework and it's browsable API, you will need to add APIView to your action classfrommultiactionimportBaseActionfromdjango.contrib.auth.modelsimportUserfromrest_framework.responseimportResponsefromrest_framework.viewsimportAPIViewclassUserAction(BaseAction,APIView):defcreate_user(self,request,*args,**kwargs):username=request.GET.get('username')user=User.objects.create(username=username)returnResponse(data={"id":user.id,"username":user.username},status=201)You can checkReferencefor more usageContributeWell, no big drama, fork the repo and make pull requests.Follow me (I am not boring, I promise)TwitterGithub
Package: django-multi-auth-token
django-multi-auth-tokenThis package allows multi token authentication for Django Rest Framework(DRF)Quick start1. Add “multi_auth_token” to your INSTALLED_APPS setting like this::
``
INSTALLED_APPS = [
…
‘multi_auth_token’,
]
``2. Add “multi_auth_token.authentication.MultiTokenAuthentication” to “DEFAULT_AUTHENTICATION_CLASSES” like this:
``
REST_FRAMWORK = {
‘DEFAULT_AUTHENTICATION_CLASSES’: [
‘multi_auth_token.authentication.MultiTokenAuthentication’,
…
]
}
``3. Migrate
``
python manage.py migrate
``IMPORTANTDO NOT add “rest_framework.authtoken” to your INSTALLED_APPS.DO NOT add “rest_framework.authentication.TokenAuthentication” to DEFAULT_AUTHENTICATION_CLASSESTODOChangelog1.0.0 - 2023-03-01 Arindam Dutta - First releaseCopyright(c) 2023 Arindam Dutta
Package: django-multiblogs
Django multiblogs==================Built on the ArticleBase model in the One Cardinal fork of [django-articles](http://github.com/powellc/django-articles/), multiblogsallows for multiple "sets" of blogs. Motivated by requests for both teacher and student blogs, and the need to have them segregatedon the website, multiblogs allows for multiple students to have their own blogs and to group them under one url.URL examples of this scenario, when app is wired up to the base url of the site:```http://yourschool.com/student-voices/the-more-you-know/2011/our-new-principal/http://yourschool.com/grade-7/fairys-and-goblins/2011/how-to-slay-werewolves/http://yourschool.com/artsy-fartsy/photos-n-more/```Maybe you don't need blog sets? Just multiple different blogs. That's cool. Just go ahead and set your particluar blog to be partof no set and it will hookup to the default url:http://yourschool.com/awesome-blog/2011/one-great-post/Of course, you can't mix and match that kind of thing, as you need to set the variable ```MULTIBLOGS_WITHOUT_SETS = TRUE``` so that wecan properly re-route urls and what-not.### Big, huge caveat:This app was built with a custom version of django-articles. The Articlemodel in codekoala's project is awesome, but a bitch to reuse elsewhereon a site, as Articles would get listed all over the place if they weresave once. My fork of[django-articles](http://github.com/powellc/django-articles) creates anabstract base class, ArticleBase, which multiblogs uses to do most ofit's lifting. You can "pip install" this fork using my pypi server atpypi.onecardinal.com.Install---------```pip install django-multiblogs```Else you could follow whatever procedure you use to install python packakges (easy_install, etc)Configuration--------------Currently there is little to configure. The important part is to wire it up in your django project:```INSTALLED_APPS = (...'multiblogs',...)```Also, set:```MULTIBLOGS_WITHOUT_SETS= TRUE```If you do not want the infinite power of blog sets to go along with your multiple blogs.In your urls:```urlpatterns += patterns('',...(r'^blogs/', include('multiblogs.urls')),...)```Templates (& URLs)--------------------All templates go in a 'multiblogs' directory in your TEMPLATE_DIR:```blog_set_list.html (/)blog_set_detail.html (/<blog-set-slug>/)blog_detail.html (/<blog-set-slug>/<blog-slug>/)post_year_archive.html (/<blog-set-slug>/<blog-slug>/<YYYY?year>/)post_detail.html (/<blog-set-slug>/<blog-slug>/<YYYY?year>/<slug>/)```
Package: django-multi-captcha-admin
django-multi-captcha-adminEasy added captcha to Django administration login page.DependencyTo use this module you need to install django and one of the captcha engines, which you can install it with easy_install or pip.InstallationInstall:pip install django-multi-captcha-adminif you are using python 2 then install version 1.0.0 (pip install django-multi-captcha-admin==1.0.0)Add'multi_captcha_admin'to yourINSTALLED_APPSsetting before'django.contrib.admin'app.INSTALLED_APPS=[...'multi_captcha_admin','django.contrib.admin',...]EnginesWe support three famous engines to render CAPTCHA. You need to install one of them, then add it to your django project according to their documents.simple-captcharecaptcharecaptcha2For more information, please go to the engine site.Then add the following to yoursettings.pywith the name of the installed engine:MULTI_CAPTCHA_ADMIN={'engine':'recaptcha2',}Resultsrecaptcha2recaptchasimple captcha
Package: django-multicurrency
Django MulticurrencySimple model multicurrency application for DjangoA brief overviewQuick startInstallation via pippip install django-multicurrencyAdd the following settings:Install multicurrency appINSTALLED_APPS += (
    'multicurrency',
)Add currencies list and Exchange model to settingsMULTICURRENCY_CURRENCIES = ['UAH', 'EUR', 'USD']
MULTICURRENCY_EXCHANGER = 'shop.models.ExchangeRate'Creating modelsCreate Exchange modelExchange model must contains staticmethod "get_exchange_rate", which must return exchange rate for two input currenciesfrom django.db import models
from django.utils.translation import gettext, gettext_lazy as _
from multicurrency.models import CURRENCIES


class ExchangeRate(models.Model):
    currency_from = models.CharField(_('Currency'),
                                    max_length=3,
                                    choices=CURRENCIES,
                                    db_index=True,
                                    null=False)
    currency_to = models.CharField(_('Currency'),
                                    max_length=3,
                                    choices=CURRENCIES,
                                    db_index=True,
                                    null=False)
    exchange_rate = models.FloatField(_('Exchange rate'),
                                    null=False)
    created_at = models.DateTimeField(_('Created at'),
                                    blank=True,
                                    null=True,
                                    auto_now_add=True)

    @staticmethod
    def get_exchange_rate(currency_from:str, currency_to:str):
        try:
            return ExchangeRate.objects.filter(
                currency_from=currency_from.lower(),
                currency_to=currency_to.lower()
            ).latest('created_at').exchange_rate
        except ExchangeRate.DoesNotExist:
            return None

    def __str__(self) -> str:
        return f"{self.get_currency_from_display()} -> " + \
               f"{self.get_currency_to_display()} {self.exchange_rate}"Create Price modelfrom django.db import models

from multicurrency.fields import MultiCurrencyPriceField
from multicurrency.models import MulticurrencyPriceModelMixin

class Product(MulticurrencyPriceModelMixin):
    title = models.CharField()
    price = MultiCurrencyPriceField(verbose_name="Product price")MultiCurrencyPriceField accept as kwargs:verbose_namenullblankAccessing fieldsMultiCurrencyPriceField has 3 methods to access price fields:PriceModel.create_<price_field_title>(price_field_title, currency, amount)PriceModel.update_<price_field_title>(price_field_title, currency, amount)PriceModel.delete_<price_field_title>(price_field_title)>>> from shop.models import Product
>>> product = Product.objects.create(title='Jeans')
>>> product.create_price('price','USD',10)
<ProductPrice: EUR(11.7) USD(10)>
>>> product.update_price('price','USD',20)
<ProductPrice: EUR(23.4) USD(20)>
>>> product.delete_price('price')
None
Package: django-multidatabase-queryset
django-multidatabase-querysetUse multi database as one.It's a common scenario that you want tostore hot data in the default database (using SSD) andstore cold data in the db_cold database (using HDD).You want to use it like normal queryset without considering it.Table of ContentsInstallationLicenseUsage# add django_multidatabase_queryset to your project apps
INSTALLED_APPS = [
    ...
    "django_multidatabase_queryset",
]

# inherit the django_multidatabase_queryset.models.MultiDataBaseModel, set the database used
class UserAction(MultiDataBaseModel):
    DATABASES = ["default", "db_cold"]
    type = models.TextField(default="")
    detail = models.JSONField(default=dict)

# Use the objects as normal objects
data1 = UserAction(id=1, type="type4")
data1.save(using="default")
data2 = UserAction(id=2, type="type3")
data2.save(using="db_cold")
data3 = UserAction(id=3, type="type1")
data3.save(using="db_cold")
order_qs = UserAction.objects.order_by(
    "type", "pk")
data = list(order_qs)
LOGGER.info(data)
self.assertEqual(data[0].type, "type1")
self.assertEqual(data[1].type, "type3")
self.assertEqual(data[2].type, "type4")
self.assertEqual(order_qs.count(), 3)Installationpip install django-multidatabase-querysetLicensedjango-multidatabase-querysetis distributed under the terms of theMITlicense.TODOmulti queryset slice
Package: django-multidb
django-multidbConfigure different apps or models to different database instances.Django settingsDATABASES={"default":{"ENGINE":"django.db.backends.sqlite3","NAME":data_dir/"default.sqlite3",},"db1":{"ENGINE":"django.db.backends.sqlite3","NAME":data_dir/"db1.sqlite3",},"db2":{"ENGINE":"django.db.backends.sqlite3","NAME":data_dir/"db2.sqlite3",},"db3":{"ENGINE":"djongo","NAME":"db3",}}Configure different models to different database instances.DATABASE_ROUTERS=["django_multidb.routers.DatabaseModelsRouter"]DATABASE_MODELS_MAPPING={"permission":"db1","role":"db2"}The Permission model uses db1, and the Role model uses db2. Run the migrate command to create tables.pythonmanage.pymigrate--database=db1# create permissionpythonmanage.pymigrate--database=db2# create roleConfigure different apps to different database instances.DATABASE_ROUTERS=["django_multidb.routers.DatabaseAppsRouter"]DATABASE_APPS_MAPPING={"authz":"db1","order":"db2"}The app authz uses db1 instance, and the order uses db2 instance. Run the migrate command to create tables.
cpythonmanage.pymigrate--database=db1# create all tables for the authz app.pythonmanage.pymigrate--database=db2# Create all tables for the order app.Tested association queries and deletions between different SQLite instances and MongoDB. More use cases can be referred to in the tests.About the Queryset.filter methodDue to the involvement of cross-database instance querying, even direct associations across different database architectures, the filter method has been overridden.First, query the IDs of data in the associated table and then perform a query on the main table using an IN condition with these IDs, rather than using JOIN syntax for the query.
Package: django-multi-db-relation
# django-multi-db-relation> Queryset optimization supports for multi database spanning relations between Django models.## Requirements- Python (>= 3.5)- Django (>= 1.10)## Installation```shpip install django-multi-db-relation```## UsageFor models```pythonclass ModelA(models.Model):name = models.CharField(max_length=10)class ModelB(models.Model):a = models.ForeignKey(ModelA, on_delete=models.DO_NOTHING)class ModelC(models.Model):b = models.ForeignKey(ModelB, on_delete=models.DO_NOTHING, db_constraint=False)```suppose that `ModelA` and `ModelB` is routed to `db1` and `ModelC` to `db2`.We **cannot** run a queryset with `select_related()`.```python>>> ModelC.objects.select_related('b') # Table not found```In this case, modify `ModelC` like:```pythonfrom multi_db_relation.mixins import ExternalDbQuerySetMixinclass ModelCQuerySet(ExternalDbQuerySetMixin, models.QuerySet):passclass ModelC(models.Model):b = models.ForeignKey(ModelB, on_delete=models.DO_NOTHING, db_constraint=False)objects = models.Manager.from_queryset(queryset_class=ModelCQuerySet)()class Meta:external_db_fields = ['b']```then:```python>>> ModelC.objects.select_related('b') # Number of queries is optimized from O(n) to O(1)>>> ModelC.objects.select_related('b__a') # Also works well```## License- See [LICENSE](LICENSE)
Package: django-multidomain
Django application, implement multi domain concept. You can choose your url config according to your domain host.InstallationYou can install the most recentDjango Multi Domainversion using pip:pip install django-multidomainSetupNOTE: The following settings should be added to the project file ‘settings.py’.Add ‘multidomain’ to ‘’INSTALLED_APPS’’:INSTALLED_APPS += ( 'multidomain', )Add ‘multidomain.middleware.DomainMiddleware’ to ‘’MIDDLEWARE_CLASSES’’:MIDDLEWARE_CLASSES += ( 'multidomain.middleware.DomainMiddleware', )Create a file for each domain you have (For example: ‘domain-one.dev’ and ‘domain-two.dev’):* urls.py   (by default)
    from django.conf.urls import patterns, include, url
    from django.contrib import admin
    urlpatterns = patterns('',
        url(r'^admin/', include(admin.site.urls)),
    )

* urls-one.py
    from django.conf.urls import patterns, include, url
    import one.urls
    urlpatterns = patterns(
        '',
        url(r'^', include(one.urls, namespace='one')),
    )

* urls-two.py
    from django.conf.urls import patterns, include, url
    import two.urls
    urlpatterns = patterns(
        '',
        url(r'^', include(two.urls, namespace='one')),
    )Declare host/domain urlconfig tuple ‘’URL_CONFIG’’:URL_CONFIG = (
    (r'^(.+\.)?domain-one\.dev', 'urls-one'),
    (r'^(.+\.)?domain-two\.dev', 'urls-two'),
)

ROOT_URLCONF = 'urls'UsageIt should create the following structure:project_django/
| -- __init__.py
| -- settings.py
| -- wsgi.py
| -- urls-one.py
| -- urls-two.py
| -- urls.py        (default/optional)NOTE: We use ‘’django-theming’’ library to manage multiple teming.
(https://github.com/achavezu89/django-theming)ContributingDevelopment ofdjango-multidomainhappens at github:https://github.com/cyacarinic/django-multidomainCreditsClaudio Yacarini:https://github.com/cyacarinic/
Package: django-multi-domains
django-multi-domainsThis Django App sets specificURL Confsfor configured domains.After all, the app has only a small middleware.Installationpipinstalldjango-multi-domainsSetupThe following configurations should be added in theDjango SettingsModule.Add"multi_domains"toINSTALLED_APPSINSTALLED_APPS=["...","multi_domains",]Add middleware"multi_domains.middleware.MultiDomainsMiddleware"to the beginning of theMIDDLEWAREMIDDLEWARE=["multi_domains.middleware.MultiDomainsMiddleware","...",]Define the mapping of domain and urlconfMULTI_DOMAINSMULTI_DOMAINS={"api.example.com":"api.urls","shop.example.com":"shop.urls",}If no mapping is set for a domain,ROOT_URLCONFis used as a fallback.
Package: django-multi-email-field
Field and widget to store a list of e-mail addresses in aDjangoproject.It provides:A form field and a form widget to edit a list of e-mails in a Django form;A model field to store the captured list of e-mails;COMPATIBILITYPython 2.7 and 3.5+Django 1.8+, 2.0+ and 3.0+INSTALLFor now:pip install django-multi-email-fieldUSAGEAddmulti_email_fieldto yourINSTALLED_APPS:# settings.py
INSTALLED_APPS = (
...
'multi_email_field',
)Use the provided form field and widget:# forms.py
from django import forms
from multi_email_field.forms import MultiEmailField

class SendMessageForm(forms.Form):
    emails = MultiEmailField()IN YOUR MODELSIf you want to store a list of e-mails, you can use this:from django.db import models
from multi_email_field.fields import MultiEmailField

class ContactModel(models.Model):
    emails = MultiEmailField()AUTHORSCreated byFlorent LebretonMaintained byMakina Corpus
Package: django-multi-email-field_rerelease
Field and widget to store a list of e-mail addresses in aDjangoprojects.It provides:A form field and a form widget to edit a list of e-mails in a Django form;A model field to store the captured list of e-mails;COMPATIBILITYPython 2.7/3.3/3.4/3.5Django 1.8/1.9/1.10INSTALLFor now:pip install django-multi-email-fieldUSAGEAddmulti_email_fieldto yourINSTALLED_APPS:# settings.py
INSTALLED_APPS = (
...
'multi_email_field',
)Use provided form field and widget:# forms.py
from django import forms
from multi_email_field.forms import MultiEmailField

class SendMessageForm(forms.Form):
    emails = MultiEmailField()IN YOUR MODELSIf you wan to store list of e-mails, you can use this:from django.db import models
from multi_email_field.fields import MultiEmailField

class ContactModel(models.Model):
    emails = MultiEmailField()AUTHORSFlorent Lebreton <florent.lebreton@makina-corpus.com>CHANGELOG0.5 (2016-10-28)Django 1.10 compatibility** Drop support **Django < 1.8 is no longer supported0.4 (2016-04-10)Better Django (1.8/1.9) and Python (3.5) compatibility0.3.1 (2014-12-18)** New **South is not required anymore0.3 (2014-12-05)** New **Add support for Python 3Add support for Django 1.70.2 (2014-04-08)** Bugfixes **Stupid blocking bad call0.1 (2014-04-07)Initial release
Package: django_multifield_clean
# Django multi field form validation<https://github.com/aumo/django_multifield_clean>Provides a Django form mixin that allows declaring validation methods(similar to the Django `Form.clean_<field_name>()` methods) working on multiplefields, allowing less boilerplate code in `Form.clean()`.*Tested on Django 1.7, 1.8 and Python 2.7, 3.2, 3.3, 3.4*## Installation`pip install django_multifield_clean`## UsageMake your form inherit from the `multifieldclean.forms.MultiFieldCleanFormMixin` mixin. Note that the mixin must come **before** the Django form class.Declare methods starting with `MULTIFIELD_CLEAN_METHOD_PREFIX` (default is `multi_clean`) which arguments are named after field names.Those methods will be called during the form validation process, after `Form.clean()`, with the field values their arguments are named after as parameters.If an argument has no default value, the validation method is called only if the field it is refering to has a value.Example:from django import formsfrom django.core.exceptions import Validationerrorfrom multifieldclean.forms import MultiFieldCleanFormMixin# The mixin must be placed before 'forms.Form'# so it can override its methods.class HolidaysForm(MultiFieldCleanFormMixin, forms.Form):start = forms.IntegerField()end = forms.IntegerField()# Any method starting with "multiclean" will be# interpreted as a multi field validation method.# The method will only be called only if 'start' and# 'end' have values.def multiclean_holidays_end_after_they_start(self, start, end):if start > end:self.add_error('end',ValidationError('These holidays end before they even start!'))### Configuration* `MULTIFIELD_CLEAN_METHOD_PREFIX`: modify the prefix used to detect validation methods, default is `multiclean`.## Why?I often found myself writing a lot of boilerplate code when overriding the `Form.clean()` method, for example:def clean(self):start = self.cleaned_data.get('start')end = self.cleaned_data.get('end')if start and end:if start > end:# etc...It is boring to write and harder to read. This package tries to provide a solution to this issue.## ContributingPull requests are welcome.Runnig the tests:* To run the full suite, use `tox`.* To run them for your current environment:* Install test requirements `pip install -r test-requirements.txt`* Install the targeted Django version.* Run `py.test`* Use `py.test --cov multifieldclean` to get the coverage report.
Package: django-multiforeignkey
django-multiforeignkeyDjango ForeignKey that links to one of several specified models:classComment(models.Model):user=models.ForeignKey(User)text=models.TextField()# users may leave comments for blog posts, articles or votingsobject=MultiForeignKey(Post,Article,Voting)UnlikeGenericForeignKey, the field uses native database foreign keys and provides maximum speed and reliability.WARNINGThis is a preliminary alpha version which most probably doesn’t fully work as advertised. I had to publish it unfinished because I had to use it in my project.Installationpip install django-multiforeignkeyUsageAddmultiforeignkeytoINSTALLED_APPS:# settings.pyINSTALLED_APPS=[...'multiforeignkey',]Add a field to your models:# comments/models.pyfrommultiforeignkey.modelsimportMultiForeignKeyclassComment(models.Model):user=models.ForeignKey(User)text=models.TextField()# users may leave comments for blog posts, articles or votingsobject=MultiForeignKey(Post,Article,Voting)Create the corresponding database tables:./manage.pymakemigrations&&./manage.pymigrateUse the new field as if it were a real database field:comment=Comment.objects.filter(object=post)assertcomment.objectispostcomment.object=votingassertcomment.objectisvotingcomment.save()or use specific subfields:comment=Comment.objects.filter(post=post)assertcomment.postispostassertcomment.articleisNoneassertcomment.votingisNonecomment.voting=votingassertcomment.postisNoneassertcomment.articleisNoneassertcomment.votingisvotingcomment.save()