[PYTHON] The story of Django creating a library that might be a little more useful

In the last April of Heisei (April 27, 2019), Django released a library that may be a little useful, and the other day it exceeded 10,000 DL, so I would like to write an article.

Django-Boost

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

Why did you make it in the first place?

At INIAD, I had the opportunity to learn the Python web application framework Django in a lecture, so I decided to make it convenient to use the Django I used at that time.

What can i do?

It's a little easier to do what you want to do when developing with Django. In particular,

--Easy to use users who log in with their email address --Python built-in functions can be used in Django temptate --You can write the URL definition in an easy-to-read manner --Can throw exceptions other than Http404 --You can create a page that requires re-authentication at regular intervals. --Touch the information of the logged-in user in the Form class --Deploying an application on heroku is a little easier

There are many other small functions, but I will omit them this time because they are detailed and sober. For more information, see Documentation (https://django-boost.readthedocs.io/).

Introduction

$ pip install django_boost

Enter with pip.

Setting

Add settings to enable django_boost in your Django project.

settings.py




INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_boost', #Postscript
]

Introduction for each function

Users who log in with their email address

Add the following contents to the configuration file.

settings.py


AUTH_USER_MODEL = 'django_boost.EmailUser'

Replace the standard Django user model with users who log in with their email address instead of their username. It has the same fields as the standard Django user model.

Use Python built-in functions in Django temptate

By adding the following description to your template file, you can use Python's built-in functions as filters and tags in your Django template.

template.html


{% load boost %}

List of Python built-in functions https://docs.python.org/ja/3/library/functions.html

Personally, I often use the format function when formatting strings.

{% load boost %}

{{ value|format:"," }} {#Display numbers every 3 digits separated by commas#}

zip is also quite convenient. Also, during development, I think it's convenient to see the list of variable types and attributes in the template, such as type and dir.

Although it is not a built-in function, there are also tags that allow you to create objects from string literals.

In the example below, a list is created.

template.html


{%load boost %}

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

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

Write the URL definition in an easy-to-read manner

If you create multiple models for one application, ʻurl patterns` will become harder to see. However, it can be used when it is troublesome to divide the file.

urls.py


from django_boost.urls import UrlSet

class YourModelUrlSet(UrlSet):
    app_name = "YourModel"
    urlpatterns = [
        path('xxx/', ..., name="XXX")
        path('yyy/', ..., name="YYY")
        path('zzz/', ..., name="ZZZ")
    ]

urlpatterns = [
    path('path/to/model/', include(YourModelUrlSet))
]

It will be easier to see if you divide it by CRUD view of each model. I think it's also convenient to be able to separate the namespace for each model.

Throw an exception other than Http404

I think it's a good idea to issue a 404 when you don't meet the viewing permission requirements. Other exceptions can be thrown as well.

To use it, you need to add a little to the configuration file.

settings.py


MIDDLEWARE = [
    'django_boost.middleware.HttpStatusCodeExceptionMiddleware',  #Postscript
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

I added one middleware.

In this state, if you throw an exception in the process of view, the status code will be returned. The following example throws a Http302 exception to redirect.

views.py


from django.shortcuts import render
from django_boost.http.response import Http302

def my_view(request):
  if request.user.email == "":
     raise Http302("/register/email/")
  return render(request, "mypage.html")

In addition to 302, it covers most status codes.

If you want to use a custom template, place [status code] .html directly under the templates directory and it will be used.

Page requesting re-authentication at regular intervals

If you are creating a View on a class basis, you can create a page that requires authentication at regular intervals by inheriting the mixin class as shown below.

view.py


from datetime import timedelta
from django_boost.views.mixins import ReAuthenticationRequiredMixin

class MyView(ReAuthenticationRequiredMixin,TemplateView):
    template_name = '...'
    auth_unnecessary = timedelta(hours=1)

Class variable ʻauth_unnecessary` By setting the re-authentication interval, re-authentication will be requested when there is a period longer than the set interval from the last login time.

For ʻauth_unnecessary, you can specify the number of seconds with ʻint, or you can specify it with timedelta.

Touch the information of the logged-in user in the Form class

When validating a form, you often want to change the validation conditions for each user.

In such a case, by inheriting the following mixin classes to the Form class and View class respectively, you can touch the user information with self.user from within the form class.

forms.py


from django import forms
from django_boost.forms.mixins import FormUserKwargsMixin

class MyForm(FormUserKwargsMixin,Form):
   email = forms.EmailField()

   def email_clean(self):
      if self.user.email: #Email address of the logged-in user
          ...
      ...

views.py


form django_boost.views.mixins import ViewUserKwargsMixin
from .forms import MyForm

class MyView(ViewUserKwargsMixin,FormView):
   form_class = MyForm
   ...

A little easier to deploy your application on heroku

You can use a command that automatically generates the configuration files needed to deploy a Django application on heroku.

$ python manage.py support_heroku
Generated : /Users/username/project/Procfile
Generated : /Users/username/project/runtime.txt
Generated : /Users/username/project/requirements.txt

Procfile, runtime.txt, requirements.txt are automatically generated.

If a file with the same name exists, it will not be generated, so if you want to overwrite it and generate it, add the --overwrite option.

$ python manage.py support_heroku --overwrite

Finally

As I mentioned at the beginning, there are many other small and sober features, so if you are interested, please see Documentation. Please give me.

Developers will be delighted to receive the stars! https://github.com/ChanTsune/django-boost

Recommended Posts

The story of Django creating a library that might be a little more useful
The story of creating a site that lists the release dates of books
The story of making a web application that records extensive reading with Django
A collection of resources that may be useful for creating and expanding dotfiles
A story that reduces the effort of operation / maintenance
A story that analyzed the delivery of Nico Nama.
4 boxes that might be useful for the Pepper hackathon
The story of creating a VIP channel for in-house chatwork
The story of a Django model field disappearing from a class
The story of creating a database using the Google Analytics API
The story of writing a program
A story stuck with the installation of the machine learning library JAX
The story of making a module that skips mail with python
Here's a summary of things that might be useful when dealing with complex numbers in Python
A story that is a little addicted to the authority of the directory specified by expdp (for beginners)
The story of creating a bot that displays active members in a specific channel of slack with python
[Python] A program that calculates the number of socks to be paired
The story of developing a web application that automatically generates catchphrases [MeCab]
A note about the functions of the Linux standard library that handles time
The story of making a package that speeds up the operation of Juman (Juman ++) & KNP
The story of blackjack A processing (python)
The story of using mysqlclient because PyMySQL cannot be used with Django 2.2
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
The story of creating Botonyan that returns the contents of Google Docs in response to a specific keyword on Slack
The story of creating (probably) the smallest skill that implements personalization and in-skill billing
The story of IPv6 address that I want to keep at a minimum
The story of making a box that interconnects Pepper's AL Memory and MQTT
The story that performance could be improved just by changing the dtype of numpy
The story of making a Line Bot that tells us the schedule of competitive programming
DJango Memo: From the beginning (creating a view)
The story of making a lie news generator
Django REST framework A little useful to know.
The story of viewing media files in Django
A story of creating 16 * 16 dots from a Digimon photo
The story of making a mel icon generator
A regular expression that finds N or more consecutive substrings of the same character
The story of Linux that I want to teach myself half a year ago
An article that gives you a little understanding of the rigid sphere collision algorithm
[Caution] When creating a binary image (1bit / pixel), be aware of the file format!
The story of launching a Minecraft server from Discord
[Python] A program that counts the number of valleys
Be careful when differentiating the eigenvectors of a matrix
Add a list of numpy library functions little by little --a
# Function that returns the character code of a string
The story of making a music generation neural network
A story that struggled with the common set HTTP_PROXY = ~
DJango Note: From the beginning (creating a view from a template)
Generate that shape of the bottom of a PET bottle
A story about changing the master name of BlueZ
The story that the return value of tape.gradient () was None
Zip 4 Gbyte problem is a story of the past
The story that Japanese output was confused with Django
[Python] A program that compares the positions of kangaroos.
Now in Singapore The story of creating a LineBot and wanting to do a memorable job
The story of creating a "spirit and time chat room" exclusively for engineers in the company
A library that monitors the life and death of other machines by pinging from Python
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
[Python] A program to find the number of apples and oranges that can be harvested
The story of sys.path.append ()
A tool that automatically turns the gacha of a social game
Add a list of numpy library functions little by little --- b