How to add Matplotlib to Django

One thing in official docs was forgotten – you need install django-matplotlib and matplotlib:

pip install django-matplotlib
pip install matplotlib

Do this in your venv!

Then add to settings.py:

INSTALLED_APPS = [
            ...
            'django_matplotlib',
            ...
]

AND

# -----------
# models.py
# -----------

from django.db import models
from django_matplotlib import MatplotlibFigureField

class MyModel(models.Model):
    figure = MatplotlibFigureField(figure='my_figure')

# -----------
# figures.py lives in the same folder as models.py
# -----------

import matplotlib.pyplot as plt

def my_figure():
    fig, ax = plt.subplots()
    ax.plot([1, 3, 4], [3, 2, 5])
    return fig

# --------
# admin.py
# --------

from django.contrib import admin
from .models import MyModel

admin.site.register(MyModel)

Now you can go to /admin of your project and add an example model:

See also  Days counting in Django model for graph generation
Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *