Django's recommended library

Friday I / O. At Wamuu Co., Ltd., every Friday is a day when we work on what we are interested in and output the results in some way. Everyone should do what they like on Friday!

Introduction

Nowadays, there are various useful languages such as Golang, but if you want to make a web application, it is the strongest (I personally think) Python Django. This time, I've summarized the libraries that I always use when creating web applications with Django.

django-cacheops

https://github.com/Suor/django-cacheops

It is a library that caches DB access via ORM without permission. It is very convenient because it will be good just by putting it in and setting it a little. In addition, there are also Function Cache and View Cache mechanisms, so it feels good to use this for the time being.

django-choices

https://github.com/bigjason/django-choices

A library that allows you to write Model and Form Choices neatly.

#How to write ordinary Choices
class Person(models.Model):
    # Choices
    PERSON_TYPE = (
        ("C", "Customer"),
        ("E", "Employee"),
        ("G", "Groundhog"),
    )

    # Fields
    name = models.CharField(max_length=32)
    type = models.CharField(max_length=1, choices=PERSON_TYPE)
# django-When using choices
from djchoices import DjangoChoices, ChoiceItem

class Person(models.Model):
    # Choices
    class PersonType(DjangoChoices):
        customer = ChoiceItem("C")
        employee = ChoiceItem("E")
        groundhog = ChoiceItem("G")

    # Fields
    name = models.CharField(max_length=32)
    type = models.CharField(max_length=1, choices=PersonType.choices)

It is convenient because it can be used as a constant.

person = Person.objects.get(1)
if person.type == Person.PersonType.customer:
    pass

django-debug-toolbar

https://github.com/jazzband/django-debug-toolbar

Needless to say, the one that displays useful debugging functions on the screen. I can't work anymore without this. Put it in because of brain death.

Image

django-extensions

https://github.com/django-extensions/django-extensions/

As the name implies, a library that extends django in various ways. Add various useful commands to manage.py and Add autocomplete function to management screen or Prepare useful model fields .html) There are a lot of things to do.

The following command to display the URL list is convenient.

./manage.py show_urls

Also, there is a function called runserver_plus, but if you use this, you can debug on the error screen displayed on the browser. Will be! To use runserver_plus, you need a library called Werkzeug.

./manage.py runserver_plus 0.0.0.0:8000

runserver-plus.png

django-import-export

https://github.com/django-import-export/django-import-export

A library that allows you to import and export CSV files, etc. from the management screen. Uncles immediately Please give me a CSV file! It's convenient to put this in because it's called . It can handle formats (Excel or JSON) supported by tablib.

Image

If you use it by default, it will be wasteful and heavy, so it is a miso in the foreground, but I think you should refer to the following article.

Why django-import-export import is so slow and what to do

django-polymorphic

https://github.com/django-polymorphic/django-polymorphic

A library that you should definitely include when using Django's Multi-Table Inheritance. It will downcast the model instance without permission.

from polymorphic.models import PolymorphicModel

class Animal(PolymorphicModel):
    name = models.CharField('name', max_length=50)

class Dog(Animal):
    def say(self):
        return '{}:Wanwan'.format(self.name)

class Cat(Animal):
    def say(self):
        return '{}:Nyan'.format(self.name)

Dog.objects.create(name='Pochi')
Cat.objects.create(name='Tama')

for animal in Animal.objects.all():
    print(animal.say())  #"Wanwan" for dogs and "Nyan" for cats

django-security

https://github.com/sdelements/django-security/

A library that contains a lot of middleware for security measures. You can write it yourself, but if you already have it, it's easier to use.

django-storages

https://github.com/jschneier/django-storages

It is a convenient library to use when you want to manage uploaded files with S3. It is indispensable when the web application has a redundant configuration.

django-widget-tweaks

https://github.com/jazzband/django-widget-tweaks

I think there are times when you want to add a class when rendering a Django Form, but that's pretty annoying, isn't it? You should definitely use django-widget-tweaks` as it can be written concisely.

This is how it is written in the Django standard. .. ..

# forms.py
class LoginForm(forms.Form):
    username = forms.CharField(
        'username',
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'input-username'})
    )
    password = forms.CharField(
        'password',
        max_length=100,
        widget=forms.PasswordInput(attrs={'class': 'input-password'})
    )

---

<!-- login.html -->
<form>
    {{ form.username }}
    {{ form.passowrd }}
    <button type="submit">Login</button>
</form>

This is what you get with django-widget-tweaks.

# forms.py
class LoginForm(forms.Form):
    username = forms.CharField('username', max_length=100)
    password = forms.CharField('password', max_length=100)

---

<!-- login.html -->
{% load widget_tweaks %}
<form>
    {% render_field form.username class="input-username" %}
    {% render_field form.passowrd class="input-password" type="password" %}
    <button type="submit">Login</button>
</form>

It's nice because you can write in the atmosphere of writing HTML.

django-betterforms

https://github.com/fusionbox/django-betterforms

It's a library that allows you to create forms that can reach the itchy place. It's especially useful to have MultiForm (https://django-betterforms.readthedocs.io/en/latest/multiform.html), which allows you to use multiple Forms as a single Form.

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password')


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('first_name', 'last_name')


class UserProfileMultiForm(MultiModelForm):
    form_classes = {
        'user': UserForm,
        'profile': ProfileForm,
    }

class UserSignupView(CreateView):
    form_class = UserProfileMultiForm
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        user = form['user'].save()
        profile = form['profile'].save(commit=False)
        profile.user = user
        profile.save()
        return redirect(self.get_success_url())

djangorestframework

It's a very useful library to use when you want to create a Rest API server using Django. It's a huge library that I can't deny that it's a different framework. Since it is huge and difficult to explain, I referred to the entry of a great ancestor.

Implement API at explosive speed using Django REST Framework

FactoryBoy

https://github.com/FactoryBoy/factory_boy

It is very useful when creating the model data required for testing! You can also create related data together, so you don't have to prepare the data when writing a test.

class ProfileFactory(DjangoModelFactory):
    user = factory.SubFactory('app.users.factories.UserFactory')
    name = Faker('name')
    name_kana = Faker('kana_name')

    class Meta:
        model = Profile
        django_get_or_create = ('user',)


class UserFactory(DjangoModelFactory):
    email = Faker('email')
    password = factory.PostGenerationMethodCall('set_password', 'hogehoge')
    profile = factory.RelatedFactory(ProfileFactory, 'user')

    class Meta:
        model = User
        django_get_or_create = ('email',)


user = UserFactory()
assert user.profile.name is not None

dateutil

https://github.com/dateutil/dateutil/

Django is a Python library, but I'll write it because it's convenient. As the name implies, it is a library that provides a utility for manipulating date and time. relativedelta which is an enhanced version of timedelta .html) is convenient anyway. You can only specify timedelta up to n days, but with relativedelta you can specify n months.

assert datetime(2000, 1, 1) + relativedelta(months=1) == datetime(2000, 2, 1)
datetime(2000, 1, 31) + relativedelta(months=1) == datetime(2000, 2, 29)

Also, parser, which automatically parses the standard date and time format, is also useful.

assert parse('2000-10-15') == datetime(2000, 10, 15)

Raven (Sentry)

https://docs.sentry.io/clients/python/integrations/django/

The library is a error tracking service client, but I will introduce it because it is very convenient. It detects exceptions thrown on the web application and sends a notification to email or Slack. If you make sure that you are notified when an error occurs in the production environment, you can sneak in before the uncles get angry. You can also check the details of the error on the Sentry management screen, so you don't have to bother to search the log file. The bug response speed will be significantly improved, so please use it.

Summary

There are many other libraries in Django, so it's fun to look for them. Awesome Django has a lot of libraries, so it's a good idea to take a look.

Uncle would be happy if you could tell me "I had a useful library" or "I made it because I don't have it".

Recommended Posts

Django's recommended library
Django's ImageField