Saravanan666/pypi-org huggingface dataset:
Package: django-content-settings
Django Content Settings - the most advanced admin editable settingThedjango-content-settingsmodule is a versatile addition to the Django ecosystem, offering users the ability to easily create and manage editable variables directly from the Django admin panel. What sets this module apart is its ability to handle variables of any type without restricting their complexity. Thanks to an integrated caching system, these variables can be used efficiently in code, irrespective of their complexity.Key FeaturesType-Agnostic Variable Creation: Users can create variables of any type, making the module highly adaptable to various needs.Editability from Django Admin Panel: Seamless integration with the Django admin panel allows for effortless editing of variables.Flaxable permission model: Every setting can have own permission rule for view, edit, fetch in API and view changes history.Preview: Preview setting before apply and addition option to preview setting change right on site.Caching System: Ensures high performance, negating the impact of variable complexity on code execution speed.For the full documentation, please visithere.▶️ YouTube Video with dive deep ~ 2hHow does it lookSetup.Hereyou can get step-by-step instruction.Define the setting. To do so you need to define constant incontent_settings.pyin your app# content_settings.pyfromcontent_settings.types.basicimportSimpleStringTITLE=SimpleString("Songs",help="The title of the site")the code above defines a variableTITLE, with typeSimpleStringand default valueSongs.Migrate. In order to be able to edit data in Django Admin$pythonmanage.pymigrateTechnically, you can use variable in code even without migration. The migration is need to make variable editable in admin panelUse it in your project. That is it. You can the variableTITLEin your code.fromcontent_settings.confimportcontent_settingscontent_settings.TITLEIn template:<h2>{{CONTENT_SETTINGS.TITLE}}</h2>In API:$curlhttp://127.0.0.1/content-settings/fetch/title/Ok, I lied, in order to use in API you need to update permission from the setting:# content_settings.pyfromcontent_settings.types.basicimportSimpleStringfromcontent_settingsimportpermissionsTITLE=SimpleString("Songs",fetch_permission=permissions.any,help="The title of the site",)Simple as that, we have a lot of types for settings you can useSimpleText,SimpleHTML,SimpleInt,SimpleBool,SimpleDecimal,DateTimeString,SimpleTimedelta,SimpleYAML,SimpleJSON,SimpleCSV,DjangoTemplate,DjangoModelTemplate,SimpleEval,SimpleExecand so on...Read moreabout the types available for you.It is also very fast thanks to our caching system.Read more about it.Some fancy things you can find in ourcookbook.
Package: django-contenttype-tag
=====django-contenttype-tag=====It's easy app for get content type of instance at templates=====How to use=====1. Add 'generic_ct_tag' at INSTALLED_APPS::INSTALLED_APPS = (...'generic_ct_tag',)3. At template::{% load generic_ct %}{% content_type obj as ct %}{{ ct.app_label }}{{ ct.model }}{# or #}{% content_type obj %} {# The resulr: <app_label>.<model> #}
Package: django-context
## django-context#### `django-context` is an BSD licensed library written in Python. It could be helpful for you if you wanna set some custom context in your django app. The one of the examples is add an extra info into your logging records. Also, you can use a request object in any place of an application cause this library provides a capability to reach it out at any time during a request.### Quick start1 install the library:```bashpip install django-context```2 Add `django-context` to your INSTALLED_APPS setting like this:```PythonINSTALLED_APPS = [...django_context,]```3 Add proxy middleware to your MIDDLEWARE setting like this:```PythonMIDDLEWARE = ['django_context.middleware.ProxyMiddleware',...]```It's important to place this `ProxyMiddleware` at the first place in a `MIDDLEWARE` to allow to calculate duration of response more precisely.4 If you just want to add info about request duration and request id to your log records then you can use `GlobalWSGIMiddleware` in your `wsgi.py` like this:```Pythonapplication = GlobalWSGIMiddleware(get_wsgi_application())```5 Use this example of logging setting to set up your loggers correctly```PythonLOGGING = {'version': 1,'formatters': {'verbose': {'format': ('[django] %(levelname)s %(asctime)s'' %(name)s/%(module)s'' %(process)d/%(thread)d'' request_id: %(request_id)s'' user_id: %(user_id)s'' duration: %(response_duration)s''  %(message)s')},},'filters': {'context_filter': {'()': 'django_context.logging.ContextFilter'}},'handlers': {'console': {'level': 'INFO','class': 'logging.StreamHandler','formatter': 'verbose','filters': ['context_filter']}},'loggers': {'django_context': {'level': 'INFO','handlers': ['console'],'propagate': True,},'django': {'level': 'INFO','handlers': ['console'],'propagate': True,},}}```### Log records example<img src="./pictures/log_records_example.png" width="1200" height="130">
Package: django-context-cache
PrologDjango-context-cacheextends the Django framework with a context cache that caches data per request or per decorated block.InstallationInstalldjango-context-cachewith thepipcommand:pipinstalldjango-context-cacheAdd'context_cache.middleware.ContextCacheMiddleware'to yourMIDDLEWARE:MIDDLEWARE=['context_cache.middleware.ContextCacheMiddleware',...]UsageImagine having an function or method which result you want to cache per request:import random
import string
from context_cache.decorators import cache_for_context

@cache_for_context
def get_random_string():
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(10))If you call function get_random_string more times the value will be get from cache:def view(request):
    get_random_string() == get_random_string() # should return TrueIf you want to cache an function out of requests, for example in the django command you can use the decoratorinit_context_cache. The decorator can be used as a context processor too:from django.core.management.base import BaseCommand, CommandError
from context_cache.decorators import init_context_cache

class Command(BaseCommand):
    
    @init_context_cache
    def handle(self, *args, **options):
        get_random_string() == get_random_string() # should return True
Package: django-context-decorator
django-context-decoratoris a Python package for Django removing the need
to callsuper().get_context_data(**kwargs)in nearly every Django view.You can also read theblog postabout this package.Usagefromdjango_context_decoratorimportcontextfromdjango.utils.functionalimportcached_propertyfromdjango.views.genericimportTemplateViewclassMyView(TemplateView):template_name='path/to/template.html'@contextdefcontext_variable(self):return'context value'@context@propertydefcontext_property(self):return'context property'@context@cached_propertydefexpensive_context_property(self):return'expensive context property'Now you’ll have access to{{ context_variable }},{{ context_property }}and{{ expensive_context_property }}in your template.Please note: While this package works with the@cached_propertydecorator,
please make sure to add the@contextdecoratorabovethe@cached_propertydecorator.This is especially useful when you couple it with inheritance, because it
allows you to re-use parent class variables without having to extract them from
yourcontext. So you could write a long-form like this:fromdjango.views.genericimportTemplateViewclassBaseMixin:defget_context_data(self,**kwargs):ctx=super().get_context_data(**kwargs)ctx['var_from_base_mixin']='var_from_base_mixin'returnctxclassView1(BaseMixin,TemplateView):defget_context_data(self,**kwargs):ctx=super().get_context_data(**kwargs)ctx['var_from_view_1']='value_from_view_1'returnctxclassView2(View1):defget_context_data(self,**kwargs):ctx=super().get_context_data(**kwargs)ctx['var_from_view_2']='value_from_view_2'returnctxinstead like this:fromdjango.views.genericimportTemplateViewfromdjango_context_decoratorimportcontextclassBaseMixin:@contextdefvar_from_base_mixin(self):return'var_from_base_mixin'classView1(BaseMixin,TemplateView):@contextdefvar_from_view_1(self):return'value_from_view_1'classView2(View1):@contextdefvar_from_view_2(self):return'value_from_view_2'LimitationsDue to the usage of__set_name__, this package is limited to Python 3.6+.DevelopmentAll code resides indjango_context_decorator.py. Tests are collected bypytestfrom all files starting withtest_. To run tests, start a
virtual environment, install the dependencies, and runpytest:pip install django pytest pytest-cov
pytest --cov-report term --cov=django_context_decorator
Package: django-context-extras
django-context-extrasAuthor:George NotarasDevelopment Web Site:django-context-extras projectSource Code Repository:django-context-extras source codeDocumentation:django-context-extras documentationDownloads:django-context-extras releasesdjango-context-extras provides some extra context processors that are often needed by Django projects.Licensed under theApache License version 2.0. More licensing information
exists in thelicensesection.FeaturesThis application currently provides two extra context processors:current_siteAdds the currentsiteinstance to the template context.project_settingsAdds the project’ssettingsobject to the template context, so you can
access the project settings from within the templates.protocol_hostAdds thePROTOHOSTandFORCESECUREPROTOHOSTvariable to the template
context. The variables contain the complete URL to the host, for example:http://example.org:8080DocumentationApart from thedjango-context-extras Online Documentation, more information about the
installation, configuration and usage of this application may be available
at the project’swiki.DonationsThis software is released as free-software and provided to you at no cost. However,
a significant amount of time and effort has gone into developing this software
and writing this documentation. So, the production of this software has not
been free from cost. It is highly recommended that, if you use this softwarein production, you should consider making a donation.To make a donation, please visit the CodeTRAXdonations pagewhich contains
aPayPaldonatebutton.Thank you for considering making a donation to django-context-extras.Bugs and feature requestsIn case you run into any problems while using this application or think that
a new feature should be implemented, it is highly recommended yousubmita new
report about it at the project’sissue tracker.Using theissue trackeris the recommended way to notify the authors about
bugs or make feature requests. Also, before submitting a new report, please
make sure you have read thenew issue guidelines.SupportCodeTRAX does not provide support for django-context-extras.You can still get community support at theCommunity Support Forums:LicenseCopyright 2010 George Notaras <gnot [at] g-loaded.eu>Licensed under theApache License, Version 2.0(the “License”);
you may not use this file except in compliance with the License.Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.A copy of the License exists in the product distribution; theLICENSEfile.
For copyright and other important notes regarding this release please read
theNOTICEfile.
Package: django-contextlayers
Context Layers for Django==========================This app provides "context layers" for Django templates.  A contextlayer is a model object that contributes data to a template duringrendering.Context layers match on URL paths.  When a match is found, the modelrecord is asked for data to contribute, and that data is sent along tothe template context.Context layers have activation dates.  You can set the layer to turnon (become active) at a specific date/time, and also to turn off(become inactive).Context layers were originally developed to provide:* Additional CSS to a page; see the sample app for an implementation* Selective enabling or disabling of adverts* Conditional markup during a site beta periodThis package doesn't provide any concrete models, so you still have toprovide your own models to specify what your layers do (in otherwords, how your layers contribute to the context).  Again, see thesample app for an implementation.Install-------Pull down the app:$ pip install django-contextlayersAdd it to your `INSTALLED_APPS`:INSTALLED_APPS = (...'contextlayers')Then include the context processor in your settings:TEMPLATE_CONTEXT_PROCESSORS = (...'contextlayers.context_processors.layer_tool',)Making Your Own Layers----------------------First you define a layer class.  You'll probably want to subclass`LayerBase`, but it's not strictly necessary.  You must include a`LayerMeta` property, and you must supply a `contribute_to_context`method.  Example from the sample:from contextlayers.models import LayerBaseclass ThemeLayer(LayerBase):markup = models.TextField(...)class LayerMeta:passdef contribute_to_context(self, layer_context, global_context):layer_context.setdefault('theme', []).append(self.markup)When this layer is matched, the content of the `markup` field will be addedto the template at `layers.theme`.Next, sync your database:$ ./manage.py syncdbThe layers won't be visible until you add support to your templates.For example:{% for css in layers.theme %}{{ css|safe }}{% endfor %}What you do with `layers.*` depends on what the layer provides to thecontext and how your templates should use it.Finally, define the layer records in the Django admin.  Take note ofthe help text for the dates and path values.
Package: django-context-request
django-context-requestDjango middleware which provide request and g object. all of which are accessible everywhere, and thread isolation, just like used in flask.InstallingInstall and update using pip:pip install django-context-requestUsageAdd RequestContextMiddleware to MIDDLEWARE in settings.pyimport django_request_context

MIDDLEWARE = [
   ...
   'django_request_context.RequestContextMiddleware',
   ...
   ]You can get request and g objects anywhere in the project throughout the life cycle of the request.
just import:from django_request_context import request, gwhy do you need this?when your django project is big enough and the function call stack is deep.
if your want to get request object in the bottom of the call stack,
you need to transfer request as parameters layer-by-layer, this can help you get request directly.
the request you import from django-request-context isreadonlyobject,
if your want to convey some message you can user g object, this is awriteableobject.
the behavior of the request and g objects is exactly the same as in the flask.
Package: django-context-variables
# django-context-variablesSimple utility to help make declarative class-based views in DjangoEach method on a CBV decorated with `context_variable` is evaluated onceper instance (==request) by the `get_context_variables` function and addedto the template's context.##Usageviews.py:class MyCBV(TemplateView):template_name = "my_template.html"def get_context_data(self, **kwargs):return get_context_variables(self)@context_variabledef page(self):return get_object_or_404(MyModel, self.kwargs.get('page_id'))@context_variabledef page_title(self):return '%s - My Site' % self.page.titlemy_template.html:<html><title>{{ page_title }}</title><body>{{ page.content }}</body></html>
Package: django-continue-reading
# django-continue-reading
Templatetag for truncating blog post bodies and adding a link that says “continue reading…” which redirects the user to the absolute url or full body of the post.###Packagehttps://pypi.python.org/pypi/django-continue-reading###Installation`$ pip installdjango-continue-reading`Add the following to yourINSTALLED_APPSsection'django_continue_reading'###How it works…If your blog application has a model object that has atitleandbodyfield`title = models.CharField(max_length=250)``body =models.TextField()`You can pass the post model object and number of words you would like to truncate your post at to this templatetag`{% load continue_reading %}``{% continue_reading post 80 %}`It will then truncate the number of words in your post body and append a link to the bottomLorem ipsum dolor sit amet consectetur adipiscing elit Cras enim erat fermentum ut diam vitae dapibus vulputate erat Vestibulum ut aliquet turpis sed ultricies mauris Nullam non felis vehicula dui vulputate mattis bibendum vitae ipsum Nam vel volutpat augue nec consectetur neque Mauris at vulputate erat Aliquam erat volutpat Pellentesque eleifend molestie magna nec efficitur neque faucibus nec Aliquam convallis ultricies lorem ut malesuada lectus luctus vel Quisque volutpat tincidunt leo a hendrerit Suspendisse condimentum velit odio nec mattisjusto...continue readingThecontinue readinglink will use theabsolute_urlof your post model object to redirect the user to the full thing.
Package: django-contracts
Django ContractsThis is a lightweight (and hopefully minimally opinionated) library that
exists to make it easier to apply Django Forms to your views. If you need
more complex capabilities than what Django Forms offers then you might want
to consider something like Django REST Framework.Basic Usagefromdjango_contracts.contractsimportapply_contract@apply_contract(request_contracts={'POST':MyRequestForm},response_contracts={'POST':MyResponseForm})defmy_view(request):# If you get here then the request matched your contractdata=request.validated_data# ... do something with the dataYou can also supply a function which returns a Django Form class to use as a
contract. This is helpful if you need a form to be specific to a user.fromdjangoimportformsfromdjango_contracts.contractsimportrequest_contractdefcreate_form_for_user(user,data):classMyUserForm(forms.Form):# ...ifuser_can_do_thing:my_field=...returnMyUserForm(data)@apply_contract(request_contracts={'POST':create_form_for_user},pass_in_user=True)defmy_view(request):# ...Or if you prefer to overrideiniton the form:fromdjangoimportformsfromdjango_contracts.contractsimportapplyclassMyUserForm(forms.Form):def__init__(self,user,*args,**kwargs):super(*args,**kwargs)self.user=user@apply_contract(request_contracts={'POST':create_form_for_user},pass_in_user=True)defmy_view(request)# ...Using forms that take aUsercan be useful for filtering choice options.
Package: django-contrib-comments-auth
READMETo make sure no bad hacker adds a comment with no authentication, you have to install a small app called django-contrib-comments-auth:pip install django-contrib-comments-authAdd it to the INSTALLED_APPS:INSTALLED_APPS = (
# ...
'django.contrib.comments',
'commentsauth',
    )Add these lines to your root urls.py:urlpatterns = patterns('',
# ...
(r'^comments/', include('commentsauth.urls'),
(r'^comments/', include('django.contrib.comments.urls'))
    )It must bebeforethe django.contrib.comments.urls-directive and have the same prefix.The template for the comment-form could look like:{% load comments %}
    {% if request.user.is_authenticated %}
    <h2>Leave a comment</h2>
    {% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
    {{ form.comment }}
    {{ form.honeypot }}
    {{ form.content_type }}
    {{ form.object_pk }}
    {{ form.timestamp }}
    {{ form.security_hash }}
    <input type="submit" value="Add comment" id="id_submit" />
    </form>
    {% else %}
    <h1>Display login form or link to login page!</h1>
    {% endif %}Please make sure to have these two lines in your MIDDLEWARE_CLASSES:MIDDLEWARE_CLASSES = (
    # ...
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
    )News0.1.1Release date: 12-Aug-2010Added news to the NEWS.txt.0.1Release date: 12-Aug-2010First untested version published.
Package: django-contrib-requestprovider
descriptiongadjo.requestprovidergives access to django’s HTTPRequest
object whenever is needed, without explicitly passing it down the path of
code.usageadd gadjo’s requestprovider middleware to django’s settings.py:MIDDLEWARE_CLASSES=(
‘gadjo.requestprovider.middleware.RequestProvider’,
…
)Whenever you need the request object (from your model, form, etc):from gadjo.requestprovider.signals import get_requesthttp_request = get_request()implementation detailsbesides saving a reference to the current request, the RequestProvider
middleware also registers itself as a receiver for whoever signals that it
needs the request object.whenver a get_request() is issued, the middleware is called to process the
signal and returns the request object.
this works because the signals in django are processed synchronously.
get_request() calls send() on the request_accessor SingleHandlerSignal(Signal)
object and returns the current request to the caller.
A SingleHandlerSignal is a Signal that makes sure it will only register
authorized receivers. This is to make sure no one will register a handler
(maybe by mistake) for a request_accessor signal since this is supposed to be
handled only by our RequestProvider middleware.class SingleHandlerSignal(Signal):allowed_receiver=’gadjo.requestprovider.middleware.RequestProvider’the Signal’s connect() method is overwritten to register only allowed
receivers.TODOnothingNOTEthis is not thread-safe. however, if you are running your django apps in a threaded environment I don’t think you really know what you’re doing.