Welcome to django-boost’s documentation!

Django Boost is a collection of custom extensions for the Django Framework.

These include management commands, additional database fields, admin extensions, view mixins, form mixins and much more.

Getting Started

Getting it

You can get Django Boost by using pip:

$ pip install django-boost

If you want to install it from source, grab the git repository and run setup.py:

$ git clone git://github.com/ChanTsune/django-boost.git
$ python setup.py install

For more detailed instructions check out our Installation instructions. Enjoy.

Compatibility with versions of Python and Django

We follow the Django guidelines for supported Python and Django versions.

See more at Django Supported Versions

This might mean the django-boost may work with older or unsupported versions but we do not guarantee it and most likely will not fix bugs related to incompatibilities with older versions.

At this time we test on and thrive to support valid combinations of Python 3.5, 3.6, 3.7, 3.8 and pypy3 with Django versions 2.0 to 2.2.

Installation instructions

synopsis:Installing django-boost

Installation

For usage

You can use pip to install django-boost for usage:

$ pip install django-boost

For development

django-boost is hosted on github:

https://github.com/ChanTsune/django-boost

Source code can be accessed by performing a Git clone.

Configuration

You will need to add the django_boost application to the INSTALLED_APPS setting of your Django project settings.py file.

INSTALLED_APPS = [
    ...
    'django_boost',
]

This will make sure that Django finds the additional management commands provided by django-boost.

The next time you invoke ./manage.py help you should be able to see all the newly available commands.

Custom User

synopsis:django-boost custom user

EmailUser

Configuration

Setting of your Django project settings.py file.

AUTH_USER_MODEL = 'django_boost.EmailUser'

Replace Django default user model.

Use email address instead of username when logging in.

AbstractEmailUser

Available when you want to add a field to EmailUser.

Inherit AbstractEmailUser and add fields.

example:

from django.db import models
from django_boost.models import AbstractEmailUser

class CustomUser(AbstractEmailUser):
    is_flozen = models.BoolField(default=False)
    homepage = models.URLField()

Model mixins

synopsis:Model mixins in django-boost

UUIDModelMixin

Mixins that replace id from AutoField to UUIDField

from django.db import models
from django_boost.models import UUIDModelMixin

class Stock(UUIDModelMixin):
    name = models.CharField(max_length=128)
    count = models.IntegerField()

TimeStampModelMixin

from django.db import models
from django_boost.models.mixins import TimeStampModelMixin

class Stock(TimeStampModelMixin):
    name = models.CharField(max_length=128)
    count = models.IntegerField()

The fields posted_at and updated_at are added.

The following fields are automatically added to the above model.

posted_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

Combine

from django.db import models
from django_boost.models.mixins import UUIDModelMixin, TimeStampModelMixin

class Stock(UUIDModelMixin,TimeStampModelMixin):
    name = models.CharField(max_length=128)
    count = models.IntegerField()

Model mixins can also be combined in this way.

LogicalDeletionMixin

from django.db import models
from django_boost.models.mixins import LogicalDeletionMixin

class Store(LogicalDeletionMixin):
    name = models.CharField(max_length=128)

The field deleted_at is added to hold the date of the logical deletion.

Also, some methods are provided to distinguish between logically deleted items.

By default, the deletion process for models that inherit from this class is a logical deletion.

If you want to do physical deletion, please pass hard=True as a delete method argument.

Store.objects.delete() # logical deletion.

Store.objects.delete(hard=True) # physical deletion.

all method will get all the data as usual, including the logically deleted items.

To retrieve items that have not been logically removed, you can use the alive method.

If you want to retrieve only the logically deleted items, you can use the dead method.

Store.objects.alive() # get not logically deleted items queryset.

Store.objects.dead() # get logically deleted items queryset.

Model fields

synopsis:Model fields in django-boost

AutoOneToOneField

from django.db import models
from django_boost.models.fields import AutoOneToOneField

class UserProfile(models.Model):
    user = AutoOneToOneField(User, primary_key=True, related_name='profile')
    home_page = models.URLField(max_length=255, blank=True)

AutoOneToOneField automatically created when the target model instance does not exist when reverse access.

In the above case, when the UserProfile model is referenced from the User model, a UserProfile instance is automatically created when there is no UserProfile model associated with the User model.

ColorCodeField

from django.db import models
from django_boost.models.fields import ColorCodeField

class MyModel(models.Model):
    color = ColorCodeField()

Save hexadecimal color code string including #.

If you specify upper=True, the saved text will be capitalized.

On the other hand, specifying lower=True will 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 is upper=False, lower=Flase.

SplitDateTimeField

from django.db import models
from django_boost.models.fields import SplitDateTimeField

class MyModel(models.Model):
    date = SplitDateTimeField()

A little convenient DateTimeField.

SplitDateTimeField is the form_class of django.models.db.DateTimeField replaced with django.forms.SplitDateTimeField.

Internal DB field is the same as django.models.db.DateTimeField.

Multiple database

synopsis:Use multiple database

Use multiple database

Switch the database used for each application.

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'db2': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
    }
}

DATABASE_ROUTERS = ['django_boost.db.router.DatabaseRouter']

DATABASE_APPS_MAPPING = {
    "myapp" : "db2",
    "myapp2" : "db2"
}

In the above example, application myapp and myapp2 will use the database db2.

Other applications use the default database.

Middlewares

synopsis:Middlewares in django-boost

RedirectCorrectHostnameMiddleware

class django_boost.middleware.RedirectCorrectHostnameMiddleware(get_response=None)

Redirect to correct hostname.

if requested hostname and settings.CORRECT_HOST does not match.

You will need to add the RedirectCorrectHostnameMiddleware to the MIDDLEWARE setting of your Django project settings.py file.

MIDDLEWARE = [
    'django_boost.middleware.RedirectCorrectHostnameMiddleware',  # add
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

CORRECT_HOST = ‘sample.com’

Redirect all access to the domain specified in CORRECT_HOST

It is not redirected when DEBUG = True

This is useful when migrating domains

Originally 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 heroku.

HttpStatusCodeExceptionMiddleware

class django_boost.middleware.HttpStatusCodeExceptionMiddleware(get_response=None)

Handle status code exceptions.

similar to the Http404 exception.

You will need to add the HttpStatusCodeExceptionMiddleware to the MIDDLEWARE setting of your Django project settings.py file.

MIDDLEWARE = [
    'django_boost.middleware.HttpStatusCodeExceptionMiddleware',  # add
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

This Middleware is required when using the HttpStatusCode Exceptions.

SpaceLessMiddleware

class django_boost.middleware.SpaceLessMiddleware(get_response=None)

Middleware that remove white space in HTML.

You will need to add the SpaceLessMiddleware to the MIDDLEWARE setting of your Django project settings.py file.

MIDDLEWARE = [
    'django_boost.middleware.SpaceLessMiddleware',  # add
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

Install so that it is executed before middleware to compress such as GZipMiddleware.

HttpStatusCode Exceptions

synopsis:HttpStatusCode Exceptions like Http404 exception in django-boost

HttpStatusCode Exceptions

Provides exceptions for other status codes as well as Django’s standard Http404 exception.

from django.http import JsonResponse
from django_boost.http import Http400, Http415

def view(request):
    if request.content_type != 'application/json':
        raise Http415
    return JsonResponse({"message":"ok"})

It is necessary to set Middlewares to use.

3XX

from django_boost.http import Http301

...
  raise Http301(redirect_url, message...)

Pass the redirect URL in the first argument.

Support Http301, Http302, Http307 and Http308.

4XX

from django_boost.http import Http415

...
  raise Http415(message...)

Support Http400, Http401, Http402, Http403, Http405, Http406, Http407, Http408, Http409, Http410, Http411, Http412, Http413, Http414, Http415, Http416, Http417, Http418, Http421, Http422, Http423, Http424, Http425, Http426, Http428, Http429 , Http431 and Http451.

5XX

from django_boost.http import Http500

...
  raise Http500(message...)

Support Http500, Http501, Http502, Http503, Http504 and Http507.

Generic Views

synopsis:Generic view class in django-boost

Extended Views

from django_boost.views.generic import View

class YourView(View):

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        ## some process before view process

        ## For example, add attribute to view class

    def after_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 response

        return response

django_boost generic view (CreateView, DeleteView, DetailView, FormView, ListView, TemplateView, UpdateView, View) classes has setup and after_view_process method, These are called before and after processing of View respectively.

setup method is same as the method added in Django 2.2 .

JsonView

A generic view class that inherits JsonResponseMixin and JsonRequestMixin.

from django_boost.views.generic import JsonView

class SameAPIView(JsonView):

    def get_context_data(self, **kwargs):
        return self.json

In the above example, we just return the sent Json string as it is.

ModelCRUDViews

Provides easy creation of CRUDViews linked to model.

from django_boost.views.generic import ModelCRUDViews

class CustomerViews(ModelCRUDViews):
    model = Customer
from django.urls import path, include
from . import views

urlpatterns = [
    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.

Case of Namespaced

from django.urls import path, include
from . import views

app_name = "myapp"
urlpatterns = [
    path('views/', include(views.CustomerViews(app_name="myapp:customer").urls)),
]

In the template you can use as follows.

{% url 'myapp:customer:list' %}
{% url 'myapp:customer:create' %}
{% url 'myapp:customer:detail' %}
{% url 'myapp:customer:update' %}
{% url 'myapp:customer:delete' %}

View Mixins

synopsis:View mixin class in django-boost

Access Mixins

AllowContentTypeMixin

Restrict the content type of http request.

from django.views.generic import TemplateView
from django_boost.views.mixins import AllowContentTypeMixin

class PostView(AllowContentTypeMixin, TemplateView):
    allowed_content_types = ["application/xml"]
    template_name = "path/to/template"

Restrict request based on Content-Type of http header.

If the content type is not allowed, http415 response will be returned.

You can disable restrictions by specifying strictly = False

class django_boost.views.mixins.ReAuthenticationRequiredMixin

Require authentication again on access.

from django.views.generic import TemplateView
from django_boost.views.mixins import ReAuthenticationRequiredMixin

class RecentLoginView(ReAuthenticationRequiredMixin, TemplateView):
    template_name = "my_page.html"
    interval = 3600
from datetime import timedelta
from django.views.generic import TemplateView
from django_boost.views.mixins import ReAuthenticationRequiredMixin

class RecentLoginView(ReAuthenticationRequiredMixin,TemplateView):
    template_name = "my_page.html"
    interval = timedelta(hours=1)

interval is the grace period until recertification.

Can specify int or datetime.timedelta.

logout=True, Logout if the specified time limit has passed.

logout=False, Do not logout Even if the specified time limit has passed.

LimitedTermMixin

from datetime import datetime
from django.views.generic import TemplateView
from django_boost.views.mixins import LimitedTermMixin

class LimitedTermMixin(LimitedTermMixin, TemplateView):
    template_name = 'path/to/template'
    start_datetime = datetime(year=2019, month=1, day=1)
    end_datetime = datetime(year=2019, month=12, day=31)

Restrict the period of access.

start_datetime specifies the date and time when access will be available, and end_datetime with the last date and time when access is available.

You can change the date and time that can be accessed dynamically by overriding the get_start_datetime and get_end_datetime methods, respectively.

You can specify the exception class to be thrown when the condition accessible to exception_class is not met.

The default is the Http404 exception.

Redirect Control Mixins

DynamicRedirectMixin

You can control the redirect destination with next=~~ in the URL query string like LoginView.

from django.views,generic import FormView
from django_boost.views.mixins import DynamicRedirectMixin

class MyFormView(DynamicRedirectMixin, FormView):
    redirect_field_name = 'next' # default keyword is 'next'
    ...

You can change the query string parameter name by changing redirect_field_name.

Adittional Attribute Mixins

UserAgentMixin

from django_boost.views.generic import TemplateView
from django_boost.views.mixins import UserAgentMixin

class SameView(UserAgentMixin, TemplateView):
    template_name = "default_template"
    pc_template_name = "pc_template.html"
    tablet_template_name = "tablet_template.html"
    mobile_template_name = "mobile_template.html"

Assign user_agent attribute to self.request and switch the template file to be displayed by user agent.

If the user agent can not be determined, the template specified in template_name will be used.

pc_template_name, tablet_template_name, mobile_template_name has no arms, but template_name is required.

JsonRequestMixin

A specialized mixin for AllowContentTypeMixin for json.

from django.views.generic import TemplateView
from django_boost.views.mixins import JsonRequestMixin

class PostView(JsonRequestMixin, TemplateView):
    template_name = "path/to/template"

    def get_context_data(self,**kwargs):
        posted_data = self.json
        # {"send" : "from cliant"}
        return posted_data

You can access the dictionary object parsed from the Json string sent by the client in self.json

If you use for the purpose of API, JsonView is recommended.

ResponseMixins

JsonResponseMixin

Returns the response in Json format

from django.views.generic import TemplateView
from django_boost.views.mixins import JsonResponseMixin

class JsonResponseView(JsonResponseMixin, TemplateView):
    extra_context = {"context" : "..."}

    def get_context_data(self,**kwargs):
        context = {}
        context.update(super().get_context_data(**kwargs))
        return context

The usage of extra_context and get_context_data is basically the same as TemplateView.

The difference is that TemplateView is passed directly to the template context, whereas JsonResponseMixin is a direct response.

Specify strictly = True if you want to limit the Content-Type to Json only.

If you use for the purpose of API JsonView below is recommended.

class django_boost.views.mixins.SuperuserRequiredMixin

Request super user authority.

class django_boost.views.mixins.StaffMemberRequiredMixin

Request staff authority.

Set the class variable superuser to True to allow superuser.

Form Mixins

synopsis:Form mixin class in django-boost

MatchedObjectGetMixin

Mixin to add a method to get the queryset and object of the condition that matches the form input content.

from django import forms
from django_boost.forms.mixins import MatchedObjectGetMixin
from .models import Customer

class CustomerForm(MatchedObjectGetMixin, forms.ModelForm):
    class Meta:
        models = Customer
        fields = ('name', )
        field_lookup = {'name' : 'name__startswith'} # filter lookup kwargs

Set field_lookup to set detailed search conditions.

from django.views.generic import FormView
from .forms import CustomerForm

class CustomerSearchView(FormView):
    template_name = "form.html"
    form_class = CustomerForm

    def form_valid(self,form):
        object = form.get_object()  # get matched model object
        object_list = form.get_list()  # get matched models objects queryset

MatchedObjectMixin provides get_object and get_list methods, each of which returns a model object or queryset that matches the form input content.

RelatedModelInlineMixin

Mixin that treat two related Model’s as a single Model.

class ModelA(models.Model):
    text = models.TextField(...)


class ModelB(models.Model):
    name = models.CharField(...)
    model_a = models.OneToOneField(to=ModelA, ...)

Specify the source field name as the dictionary key and the destination field as the dictionary value.

The dictionary value must be a list or tuple.

class ModelBForm(RelatedModelInlineMixin, forms.ModelForm):
    inline_fields = {'model_a': ('text',)}

    class Meta:
        model = ModelB
        fields = ('name', )

Also can inline multiple relationships.

class MyModelForm(RelatedModelInlineMixin, forms.ModelForm):
    inline_fields = {'model_a': ('text',),
                     'model_x': ('text',)}

    class Meta:
        model = MyModel
        fields = ('name', )
class django_boost.forms.mixins.FieldRenameMixin(*args, **kwargs)

FieldRenameMixin that changes form field names.

Due to Python syntax, - cannot be included in form field names.

Use it when the value of name attribute of HTML input element includes - due to restrictions of external library.

from django import form
from django_boost.forms.mixins import FieldRenameMixin

class MyForm(FieldRenameMixin,forms.Form):
    token_id = forms.CharField()

    rename_field = {"token_id": "token-id"}

MyForm().cleaned_data["token-id"]

Form Fields

synopsis:Form field class in django-boost

ColorCodeField

class django_boost.forms.fields.ColorCodeField(*, max_length=None, min_length=None, strip=True, empty_value='', **kwargs)

Field for storing hexadecimal color code like #FFEEDD.

from django import forms
from django_boost.forms.fields import ColorCodeField

class MyForm(forms.Form):
    color = ColorCodeField()

InvertBooleanField

class django_boost.forms.fields.InvertBooleanField(*, required=True, widget=None, label=None, initial=None, help_text='', error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None)

Field that returns inverted input.

Returns false if the checkbox is checked, returns true if the checkbox is not checked.

from django import forms
from django_boost.forms.fields import InvertBooleanField

class MyForm(forms.Form):
    invert = InvertBooleanField()

PhoneNumberField

class django_boost.forms.fields.PhoneNumberField(*, max_length=None, min_length=None, strip=True, empty_value='', **kwargs)

Field for phone number.

from django import forms
from django_boost.forms.fields import PhoneNumberField

class MyForm(forms.Form):
    phone = PhoneNumberField()

Path Converters

synopsis:path converter keywords in django-boost

Enable path converter keywords

from django_boost.urls import register_boost_converters

register_boost_converters()

Example

from django.urls import path
from django_boost.urls import register_boost_converters

register_boost_converters()

urlpatterns = [
    path('bin/<bin:id>', ~~),
    path('oct/<bin:id>', ~~),
    path('hex/<bin:id>', ~~),
    path('float/<float:id>', ~~),
]

Keywords

bin

bin matches regular expression [01]+

This is passed as int type to the python program.

oct

oct match [0-7]+

This is passed as int type to the python program.

hex

hex match [0-9a-fA-F]

This is passed as int type to the python program.

bin_str

Basically the same as bin. The difference is that it is passed to the Python program as str

oct_str

Basically the same as oct. The difference is that it is passed to the Python program as str

hex_str

Basically the same as hex. The difference is that it is passed to the Python program as str

float

float match '[0-9]+([.][0-9]+)?'

This is passed as float type to the python program.

date

date matches dates that consider leap years like 'Y/m/d'

This is passed as datetime.datetime type to python program.

Shortcut Functions

synopsis:Model mixins in django-boost
from django_boost.shortcuts import (
    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 like get_object_or_404

Routing Utilitys

synopsis:urlset

UrlSet

If URLs corresponding to multiple models are described in one urls.py, it may be redundant as below.

from django.urls import path
from . import views

urlpatterns = [
    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 use UrlSet.

When the above code is rewritten using UrlSet, it becomes as follows.

from django.urls import path, include
from django_boost.urls import UrlSet

from . import views

class ModelAUrlSet(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'),
    ]

class ModelBUrlSet(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.

django_boost.urls.include_static_files(path)

Add to routing that static files under the directory specified by the absolute path.

example

import os
from django.urls import path
from django_boost.urls import include_static_files

DIR = os.path.dirname(__file__)

urlpatterns = [
    path('static_files/', include_static_files(DIR)),
]

Admin Site Utilitys

synopsis:Admin site utilitys in django-boost
django_boost.admin.sites.register_all(models, admin_class=<class 'django.contrib.admin.options.ModelAdmin'>, **options)

Easily register Models to Django admin site.

from yourapp import models
from django_boost.admin.sites import register_all

register_all(models)

Register all models defined in `models.py` in Django admin site.

Custom admin classes are also available.
from your_app import models
from your_app import admin
from django_boost.admin.sites import register_all

register_all(models, admin_class=admin.CustomAdmin)

Utilty Functions

synopsis:Utilty functions in django-boost

loop utils

Django Template like forloop

loop

from django_boost.utils import loop

for forloop, item in loop([1, 2, 3, 4, 5]):
    forloop.counter0
    forloop.counter
    forloop.revcounter0
    forloop.revcounter
    forloop.first
    forloop.last

Provides Django Template loops to Python programs.

loopfirst

Yield True when the first element of the given iterator object, False otherwise.

from django_boost.utils.functions import loopfirst

for is_first, v in loopfirst(range(5)):
    print(is_first, v)

# True 0
# False 1
# False 2
# False 3
# False 4

looplast

Yield True when the last element of the given iterator object, False otherwise.

from django_boost.utils.functions import looplast

for is_last, v in looplast(range(5)):
    print(is_last, v)

# False 0
# False 1
# False 2
# False 3
# True 4

loopfirstlast

A function combining firstloop and lastloop.

Yield True if the first and last element of the iterator object, False otherwise.

from django_boost.utils.functions import loopfirstlast

for first_or_last, v in loopfirstlast(range(5)):
    print(first_or_last, v)

# True 0
# False 1
# False 2
# False 3
# True 4

Template context

synopsis:context processor in django-boost

User Agent

Configuration

TEMPLATES = [
    {
        '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', # add
            ],
        },
    },
]

When given a user agent like 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, 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 using user-agents

Template Tags

synopsis:Template Tags in django-boost

Python built-in functions

Make Python built-in functions available in DjangoTemplate.

Some non-built-in functions are also provided as filters.

An example is isiterable filter.

Usage

{% load boost %}

isiterable

isiterable filter returns True if it filters repeatable objects, and False otherwise.

{% load boost %}

{% if object|isiterable %}
  {% for i in object %}
    <p>{{ i }}</p>
  {% endfor %}
{% else %}
  <p>{{ object }}</p>
{% endif %}

literal

Python literal from string. Using backend ast.literal_eval.

{% load boost %}

{% literal "[1, 2, 3]" as list %}

{% for i in list %}
    <p>{{ i }}</p>
{% endfor %}

chain

Concatenate iterable objects

{% load boost %}

{% chain list1 list2 as concatenated_list %}

{% for i in concatenated_list %}
  {{ i }}
{% endfor %}

chunked

Break iterable into lists of length n

{% load boost %}

{% for i in list|chunked:3 %}
  {% for j in i %}
    {{ j }}
  {% endfor %}
{% endfor %}

URL Utility

Usage

{% load boost_url %}

urlencode

URL encode the filtered string. You can specify non-conversion characters in the argument.

{% load boost_url %}

{{ url | urlencode }}

{{ url | urlencode:'abc' }}

urldecode

The reverse of urlencode.

{% load boost_url %}

{{ url | urldecode }}

replace_parameters

Replace the query string of the current page URL with the argument.

{% load boost_url %}

{# case of current page's query string is `?id=2`#}
{% replace_parameters request 'id' 1 'age' 20 %}

{# The result of replacing is `?id=1&age=20` #}

Useful for pagination.

get_querystring

return querystring value

{% load boost_url %}

{% get_querystring request 'id' %}

{# return request.GET.get('id', None) #}

Queryset Utility

Usage

{% load boost_query %}

Make the query set methods available in the template.

filter, exclude, order_by are available.

If you use the LogicalDeletionMixin, you can also use alive and dead

{% qureyset|filter:"field=value"%}

{% qureyset|exclude:"field=value"%}

{% qureyset|order_by:"field"%}

{# If it inherits LogicalDeletionMixin. #}

{% qureyset|alive %}

{% qureyset|dead %}

MimeType Utility

Usage

{% load mimetype %}

mimetype

Guess mimetype from the extension at the end of the string.

Python mimetypes.guess_type is used internally.

{{ "json"|mimetype }} {# "application/json" #}

{{ ".json"|mimetype }} {# "application/json" #}

{{ "sample.json"|mimetype }} {# "application/json" #}

Commands

synopsis:Exist commands in django-boost

adminsitelog

$ python manage.py adminsitelog

View and delete Admin Site logs.

usage: manage.py adminsitelog [-h] [--version] [-v {0,1,2,3}]
                              [--settings SETTINGS] [--pythonpath PYTHONPATH]
                              [--traceback] [--no-color] [-d]
                              [--filter FILTER [FILTER ...]]
                              [--exclude EXCLUDE [EXCLUDE ...]]
                              [--order_by ORDER_BY [ORDER_BY ...]]
                              [--name_field NAME_FIELD]

Django admin site log

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  -d, --delete          Delete displayed logs.
  --filter FILTER [FILTER ...]
                        Filter the Log to be displayed. Supported filed is
                        action_flag, action_time, change_message,
                        content_type, content_type_id, id, object_id,
                        object_repr, user, user_id. e.g.
                        "action_time>=2019-8-22"
  --exclude EXCLUDE [EXCLUDE ...]
                        Exclude the Log to be displayed. Supported filed is
                        same as --filter. e.g. "user__username=admin"
  --order_by ORDER_BY [ORDER_BY ...]
                        Order of Log to be displayed. Supported filed is
                        action_flag, action_time, change_message,
                        content_type, content_type_id, id, object_id,
                        object_repr, user, user_id. e.g. "-action_flag"
  --name_field NAME_FIELD
                        user name field. e.g. "--name_field email", "--
                        name_field profile.phone"

view all logs

$ python manage.py adminsitelog
id| action | detail | user | time
6 | Deleted | Customer object (8) | admin | 2019-08-19 14:56:29.609940+00:00
7 | Added | Customer object (11) | admin | 2019-08-20 16:12:38.902129+00:00
8 | Changed | Customer object (4) - Changed color. | admin | 2019-08-20 16:12:45.653693+00:00

filter logs

$ python manage.py adminsitelog --filter "action_time>=2019-8-01" --exclude "id=6"
id | action | detail | user | time
7 | Added | Customer object (11) | admin | 2019-08-20 16:12:38.902129+00:00
8 | Changed | Customer object (4) - Changed color. | admin | 2019-08-20 16:12:45.653693+00:00

delete all logs

$ python manage.py adminsitelog --delete

It is also possible to delete only the logs narrowed down by --filter and --exclude.

support_heroku

$ python manage.py support_heroku

Create heroku config files. Procfile, runtime.txt, requirements.txt

usage: manage.py support_heroku [-h] [--overwrite] [--no-gunicorn] [--runtime]
                                [--prockfile]
                                [--release RELEASE [RELEASE ...]]
                                [--requirments] [-q] [--version]
                                [-v {0,1,2,3}] [--settings SETTINGS]
                                [--pythonpath PYTHONPATH] [--traceback]
                                [--no-color] [--force-color] [--skip-checks]

Create a configuration file for heroku `Procfile`,`runtime.txt` and
`requirements.txt`

optional arguments:
  -h, --help            show this help message and exit
  --overwrite           Overwrite even if file exists.
  --no-gunicorn         Don't automatically add `gunicorn` to
                        `requirements.txt`.
  --runtime             Create only `runtime.txt`, By default all files are
                        created.
  --prockfile           Create only `Prockfile`, By default all files are
                        created.
  --release RELEASE [RELEASE ...]
                        Add the command to be executed in the release phase to
                        `Prockfile`
  --requirments         Create only `requirments.txt`, By default all files
                        are created.
  -q, --quit            Don't output to standard output.
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --force-color         Force colorization of the command output.
  --skip-checks         Skip system checks.

deletemigrations

$ python manage.py deletemigrations appname

Delete migration files.

usage: manage.py deletemigrations [-h] [-y] [--version] [-v {0,1,2,3}]
                                  [--settings SETTINGS]
                                  [--pythonpath PYTHONPATH] [--traceback]
                                  [--no-color] [--force-color]
                                  app_label [app_label ...]

delete migration files.

positional arguments:
  app_label             One or more application label.

optional arguments:
  -h, --help            show this help message and exit
  -y
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --force-color         Force colorization of the command output.

Indices and tables