Package: django-boost
Django-BoostDjango Boost is a collection of custom extensions for the Django Framework.DocumentationYou can view documentation online at:https://django-boost.readthedocs.io/en/latest/Or you can look at the docs/ directory in the repository.Getting Itpipinstalldjango-boostorgitclonehttps://github.com/ChanTsune/Django-Boost.git

pythonsetup.pyinstallInstalling ItTo enable django_boost in your project you need to add it to INSTALLED_APPS in your projects settings.py file:INSTALLED_APPS=[...'django_boost',...]Brief introductionEmailUsersettings.pyAUTH_USER_MODEL='django_boost.EmailUser'Replace Django default user model
Use email address instead of username when logging inAbstractEmailUserfromdjango.dbimportmodelsfromdjango_boost.modelsimportAbstractEmailUserclassCustomUser(AbstractEmailUser):is_flozen=models.BoolField(default=False)homepage=models.URLField()Available when you want to add a field to EmailUserUUIDModelMixinfromdjango.dbimportmodelsfromdjango_boost.modelsimportUUIDModelMixinclassStock(UUIDModelMixin):name=models.CharField(max_length=128)count=models.IntegerField()Mixins that replaceidfromAutoFieldtoUUIDFieldTimeStampModelMixinfromdjango.dbimportmodelsfromdjango_boost.models.mixinsimportTimeStampModelMixinclassStock(TimeStampModelMixin):name=models.CharField(max_length=128)count=models.IntegerField()The fieldsposted_atandupdated_atare added.posted_at=models.DateTimeField(auto_now_add=True)updated_at=models.DateTimeField(auto_now=True)ColorCodeFieldfromdjango.dbimportmodelsfromdjango_boost.models.fieldsimportColorCodeFieldclassMyModel(models.Model):color=ColorCodeField()Save hexadecimal color code string including #.
If you specifyupper=True, the saved text will be capitalized.
On the other hand, specifyinglower=Truewill make the saved string lower case.
You can not specify both at the same time.
If neither is set, the string is saved without any changes.
Default isupper=False,lower=Flase.SplitDateTimeFieldfromdjango.dbimportmodelsfromdjango_boost.models.fieldsimportSplitDateTimeFieldclassMyModel(models.Model):date=SplitDateTimeField()A little convenient DateTimeField.SplitDateTimeFieldis the form_class ofdjango.models.db.DateTimeFieldreplaced withdjango.forms.SplitDateTimeField.Internal DB field is the same asdjango.models.db.DateTimeField.AutoOneToOneFieldfromdjango.dbimportmodelsfromdjango_boost.models.fieldsimportAutoOneToOneFieldclassUserProfile(models.Model):user=AutoOneToOneField(User,primary_key=True,related_name='profile')home_page=models.URLField(max_length=255,blank=True)RedirectCorrectHostnameMiddlewaresettings.pyMIDDLEWARE=['django_boost.middleware.RedirectCorrectHostnameMiddleware',# django_boost'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware',...]...CORRECT_HOST='sample.com'Redirect all access to the domain specified inCORRECT_HOSTIt is not redirected whenDEBUG = TrueThis is useful when migrating domainsOriginally it should be done with server software such as nginx and apache, but it is useful when the setting is troublesome or when using services such as herokuHttpStatusCodeExceptionMiddlewaresettings.pyMIDDLEWARE=['django_boost.middleware.HttpStatusCodeExceptionMiddleware',# django_boost'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware',...]It is necessary to use theHttpStatusCode exceptionsdescribed later.HttpStatusCode ExceptionsProvides exceptions for other status codes as well as Django's standardHttp404exceptionfromdjango.httpimportJsonResponsefromdjango_boost.httpimportHttp400,Http415defview(request):ifrequest.content_type!='application/json':raiseHttp415returnJsonResponse({"message":"ok"})This Middleware is required when usingHttpStatusCodeExceptionMiddlewareUser Agent in Template contextTEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','DIRS':[],'APP_DIRS':True,'OPTIONS':{'context_processors':['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages','django_boost.context_processors.user_agent',# django boost],},},]When given a user agent likeMozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36, provide the following context to the template{'user_agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36','browser':'Chrome','device':'Other','is_bot':False,'is_email_client':False,'is_mobile':False,'is_pc':True,'is_tablet':False,'is_touch_capable':False,'os':'Mac OS X'}These information is obtained usinguser-agentsAllowContentTypeMixinRestrict the content type of http request.fromdjango.views.genericimportTemplateViewfromdjango_boost.views.mixinsimportAllowContentTypeMixinclassPostView(AllowContentTypeMixin,TemplateView):allowed_content_types=["application/xml"]template_name="path/to/template"Restrict request based onContent-Typeof http header.If the content type is not allowed, http415 response will be returned.
You can disable restrictions by specifyingstrictly = FalseLimitedTermMixinfromdatetimeimportdatetimefromdjango.views.genericimportTemplateViewfromdjango_boost.views.mixinsimportLimitedTermMixinclassLimitedTermMixin(LimitedTermMixin,TemplateView):template_name=''start_datetime=datetime(year=2019,month=1,day=1)end_datetime=datetime(year=2019,month=12,day=31)Restrict the period of access.start_datetimespecifies the date and time when access will be available, andend_datetimewith the last date and time when access is available.You can change the date and time that can be accessed dynamically by overriding theget_start_datetimeandget_end_datetimemethods, respectively.You can specify the exception class to be thrown when the condition accessible toexception_classis not met.
The default is theHttp404exception.DynamicRedirectMixinYou can control the redirect destination withnext=~in the URL query string likeLoginView.fromdjango.views,genericimportFormViewfromdjango_boost.views.mixinsimportDynamicRedirectMixinclassMyFormView(DynamicRedirectMixin,FormView):redirect_field_name='next'# default is 'next'...You can change the query string parameter name by changingredirect_field_name.UserAgentMixinfromdjango_boost.views.genericimportTemplateViewfromdjango_boost.views.mixinsimportUserAgentMixinclassSameView(UserAgentMixin,TemplateView):template_name="default_template"pc_template_name="pc_template.html"tablet_template_name="tablet_template.html"mobile_template_name="mobile_template.html"Assignuser_agentattribute toself.requestand switch the template file to be displayed by user agent.If the user agent can not be determined, the template specified intemplate_namewill be used.pc_template_name,tablet_template_name,mobile_template_namehas no arms, buttemplate_nameis required.JsonRequestMixinA specialized mixin forAllowContentTypeMixinfor json.fromdjango.views.genericimportTemplateViewfromdjango_boost.views.mixinsimportJsonRequestMixinclassPostView(JsonRequestMixin,TemplateView):template_name="path/to/template"defget_context_data(self,**kwargs):posted_data=self.json# {"send" : "from client"}returnposted_dataYou can access the dictionary object parsed from the Json string sent by the client inself.jsonIf you use for the purpose of APIJsonViewbelow is recommended.JsonResponseMixinReturns the response in Json formatfromdjango.views.genericimportTemplateViewfromdjango_boost.views.mixinsimportJsonResponseMixinclassJsonResponseView(JsonResponseMixin,TemplateView):extra_context={"context":"..."}defget_context_data(self,**kwargs):context={}context.update(super().get_context_data(**kwargs))returncontextThe usage ofextra_contextandget_context_datais basically the same asTemplateView.
The difference is thatTemplateViewis passed directly to the template context, whereasJsonResponseMixinis a direct response.Specifystrictly = Trueif you want to limit the Content-Type to Json only.If you use for the purpose of APIJsonViewbelow is recommended.MatchedObjectGetMixinObject of the condition that matches the form input content.
Or mixin to add a method to get the queryset.fromdjangoimportformsfromdjango_boost.forms.mixinsimportMatchedObjectGetMixinfrom.modelsimportCustomerclassCustomerForm(MatchedObjectGetMixin,forms.ModelForm):classMeta:models=Customerfields=('name',)field_lookup={'name':'name__startswith'}# filter lookup kwargsSetfield_lookupto set detailed search conditions.fromdjango.views.genericimportFormViewfrom.formsimportCustomerFormclassCustomerSearchView(FormView):template_name="form.html"form_class=CustomerFormdefform_valid(self,form):object=form.get_object()# get matched model objectobject_list=form.get_list()# get matched models objects querysetMatchedObjectMixinprovidesget_objectandget_listmethods, each of which returns amodel objectorquerysetthat matches the form input content.RelatedModelInlineMixinMixin that treat two relatedModel's as a singleModel.classModelA(models.Model):text=models.TextField(...)classModelB(models.Model):name=models.CharField(...)model_a=models.OneToOneField(to=ModelA,...)classModelBForm(RelatedModelInlineMixin,forms.ModelForm):inline_fields={'model_a':('text',)}classMeta:model=ModelBfields=('name',)GenericViewExtended Viewsfromdjango_boost.views.genericimportViewclassYourView(View):defsetup(self,request,*args,**kwargs):super().setup(request,*args,**kwargs)## some process before view process## For example, add attribute to view classdefafter_view_process(self,request,response,*args,**kwargs):super().after_view_process(request,response,*args,**kwargs)## some process after view process## For example, add http headers to the responsereturnresponsedjango_boost generic view (CreateView,DeleteView,DetailView,FormView,ListView,TemplateView,UpdateView,View) classes hassetupandafter_view_processmethod, These are called before and after processing of View respectively.setupmethod is same as the method added in Django 2.2 .ModelCRUDViewsProvides easy creation of CRUDViews linked to model.views.pyfromdjango_boost.views.genericimportModelCRUDViewsclassCustomerViews(ModelCRUDViews):model=Customerurls.pyfromdjango.urlsimportpath,includefrom.importviewsurlpatterns=[path('views/',include(views.CustomerViews().urls)),]In the template you can use as follows.{%url'customer:list'%}{%url'customer:create'%}{%url'customer:detail'%}{%url'customer:update'%}{%url'customer:delete'%}The name of the URL is defined under the namespace of the lower-cased model class name.Path Convertersfromdjango_boost.urlsimportregister_boost_convertersregister_boost_converters()Addhex,oct,bin,hex_str,oct_strandbin_strto path converter keyword.fromdjango.urlsimportpathfromdjango_boost.urlsimportregister_boost_convertersregister_boost_converters()urlpatterns=[path('bin/<bin:id>',~~),path('oct/<bin:id>',~~),path('hex/<bin:id>',~~),]binmatch[01]+,octmatch[0-7]+,hexmatch[0-9a-fA-F]These are passed asinttype to the python program.Keywords that end with_strare passed asstrtype to python program.Shortcut Functionsfromdjango_boost.shortcutsimport(get_list_or_default,get_list_or_exception,get_object_or_default,get_object_or_exception)my_model=MyModel.objects.get(id=1)get_object_or_default(MyModel,default=my_model,id=2)get_object_or_exception(MyModel,exception=Exception,id=2)These behave likeget_object_or_404UrlSetIf URLs corresponding to multiple models are described in oneurls.py, it may be redundant.
As below.fromdjango.urlsimportpathfrom.importviewsurlpatterns=[path('modelA/',views.ModelAListView.as_view(),name='modelA_list'),path('modelA/create/',views.ModelACreateView.as_view(),name='modelA_create'),path('modelA/<int:pk>/',views.ModelADetailView.as_view(),name='modelA_detail'),path('modelA/<int:pk>/update/',views.ModelAUpdateView.as_view(),name='modelA_update'),path('modelA/<int:pk>/delete/',views.ModelADeleteView.as_view(),name='modelA_delete'),path('modelB/',views.ModelBListView.as_view(),name='modelB_list'),path('modelB/create/',views.ModelBCreateView.as_view(),name='modelB_create'),path('modelB/<int:pk>/',views.ModelBDetailView.as_view(),name='modelB_detail'),path('modelB/<int:pk>/update/',views.ModelBUpdateView.as_view(),name='modelB_update'),path('modelB/<int:pk>/delete/',views.ModelBDeleteView.as_view(),name='modelB_delete'),]Originally it would be desirable to split the file, but doing so can lead to poor code outlook, due to the increase in files.In such cases, you can useUrlSet.When the above code is rewritten usingUrlSet, it becomes as follows.fromdjango.urlsimportpath,includefromdjango_boost.urlsimportUrlSetfrom.importviewsclassModelAUrlSet(UrlSet):app_name="ModelA"urlpatterns=[path('',views.ModelAListView.as_view(),name='list'),path('create/',views.ModelACreateView.as_view(),name='create'),path('<int:pk>/',views.ModelADetailView.as_view(),name='detail'),path('<int:pk>/update/',views.ModelAUpdateView.as_view(),name='update'),path('<int:pk>/delete/',views.ModelADeleteView.as_view(),name='delete'),]classModelBUrlSet(UrlSet):app_name="ModelB"urlpatterns=[path('',views.ModelBListView.as_view(),name='list'),path('create/',views.ModelBCreateView.as_view(),name='create'),path('<int:pk>/',views.ModelBDetailView.as_view(),name='detail'),path('<int:pk>/update/',views.ModelBUpdateView.as_view(),name='update'),path('<int:pk>/delete/',views.ModelBDeleteView.as_view(),name='delete'),]urlpatterns=[path('modelA/',include(ModelAUrlSet)),path('modelB/',include(ModelBUrlSet)),]URLs are grouped for easy reading.Admin Site UtilitiesEasily register Models to Django admin site.fromyour_appimportmodelsfromdjango_boost.admin.sitesimportregister_allregister_all(models)Register all models defined inmodels.pyin Django admin site.Custom admin classes are also available.fromyour_appimportmodelsfromyour_appimportadminfromdjango_boost.admin.sitesimportregister_allregister_all(models,admin_class=admin.CustomAdmin)Template TagsMake Python built-in functions available in DjangoTemplate.
Some non-built-in functions are also provided as filters. An example isisiterablefilter.Load filters{%loadboost%}isiterableisiterable filter returns True if it filters repeatable objects, and False otherwise.{%loadboost%}{%ifobject|isiterable%}{%foriinobject%}<p>{{i}}</p>{%endfor%}{%else%}<p>{{object}}</p>{%endif%}literalPython literal from string.
Using backendast.literal_eval.{%loadboost%}{%literal"[1, 2, 3]"aslist%}{%foriinlist%}<p>{{i}}</p>{%endfor%}URL Utility{%loadboost_url%}urlencodeURL encode the filtered string.
You can specify non-conversion characters in the argument.{%loadboost_url%}{{url|urlencode}}{{url|urlencode:'abc'}}urldecodeThe reverse ofurlencode.{%loadboost_url%}{{url|urldecode}}replace_parametersReplace the query string of the current page URL with the argument.{%loadboost_url%}{# case of current page's query string is `?id=2`#}{%replace_parametersrequest'id'1'age'20%}{# The result of replacing is `?id=1&age=20` #}Useful for pagination.Queryset Utility{%loadboost_query%}Make the query set methods available in the template.filter,exclude,order_byare available.If you use the LogicalDeletionMixin, you can also usealiveanddead{%qureyset|filter:"field=value"%}{%qureyset|exclude:"field=value"%}{%qureyset|order_by:"field"%}{# If it inherits LogicalDeletionMixin. #}{%qureyset|alive%}{%qureyset|dead%}utilty functionsloop utilsDjango Template like forloopfromdjango_boost.utilsimportloopforforloop,iteminloop([1,2,3,4,5]):forloop.counter0forloop.counterforloop.revcounter0forloop.revcounterforloop.firstforloop.lastProvides Django Template loops to Python programs.loopfirstYield True when the first element of the given iterator object, False otherwise.fromdjango_boost.utils.functionsimportloopfirstforis_first,vinloopfirst(range(5)):print(is_first,v)# True 0# False 1# False 2# False 3# False 4looplastYield True when the last element of the given iterator object, False otherwise.fromdjango_boost.utils.functionsimportlooplastforis_last,vinlooplast(range(5)):print(is_last,v)# False 0# False 1# False 2# False 3# True 4loopfirstlastA function combiningfirstloopandlastloop.Yield True if the first and last element of the iterator object, False otherwise.fromdjango_boost.utils.functionsimportloopfirstlastforfirst_or_last,vinloopfirstlast(range(5)):print(first_or_last,v)# True 0# False 1# False 2# False 3# True 4Commandsadminsitelogpythonmanage.pyadminsitelogView and delete Admin Site logs.view all logspythonmanage.pyadminsitelogid|action|detail|user|time6|Deleted|Customerobject(8)|admin|2019-08-1914:56:29.609940+00:007|Added|Customerobject(11)|admin|2019-08-2016:12:38.902129+00:008|Changed|Customerobject(4)-Changedcolor.|admin|2019-08-2016:12:45.653693+00:00filter logspythonmanage.pyadminsitelog--filter"action_time>=2019-8-01"--exclude"id=6"id|action|detail|user|time7|Added|Customerobject(11)|admin|2019-08-2016:12:38.902129+00:008|Changed|Customerobject(4)-Changedcolor.|admin|2019-08-2016:12:45.653693+00:00delete all logspythonmanage.pyadminsitelog--deleteIt is also possible to delete only the logs narrowed down by--filterand--exclude.support_herokupythonmanage.pysupport_herokuCreate heroku config files.Procfile,runtime.txt,requirements.txtFor more details.pythonmanage.pysupport_heroku-h