Советы

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Для структурирования и мониторинга рабочих процессов используют канбан-доски — например, Jira и Trello. Они особенно полезны, когда задачи состоят из множества этапов — согласования, выполнения, ревью и продакшена.

В статье рассказываем, как разработать собственную канбан-доску и развернуть ее на облачном сервере. Подробности под катом.

Текст подготовила Наталья Кайда, технический писатель Proglib. Спасибо!

С чего начнем

Мы разработаем и запустим онлайн-версию классической канбан-доски с четырьмя колонками, которые соответствуют различным стадиям выполнения задач. Карточки можно перетаскивать из одной колонки в другую, редактировать и удалять без перезагрузки страницы.

Канбан максимально использует функциональность Django — управление базой данных, формы, шаблоны, систему аутентификации и авторизации. Асинхронная передача данных и CRUD без перезагрузки доски реализованы с помощью API на Django REST Framework.

Фронтенд канбана написан на Alpine.js — это минималистичный JS-фреймворк, который по синтаксису очень похож на Vue.js, а по функциональности на jQuery. Дизайн сделан на CSS-фреймворке Tailwind, а для HTTP-запросов к бэкенду используется библиотека Axios.

Весь код для проекта находится в репозитории Kanban.

Бэкенд и API

Модель базы данных board/models.py

Поскольку в канбане фиксированное число колонок, можно обойтись одной моделью Task с полем models.TextChoices. Если нужно дать пользователям возможность создавать неограниченное количество колонок с произвольными именами (как в Trello), потребуется модель Board, с которой модель Task будет связана при помощи ForeignKey. Сериализатор в этом случае будет вложенным.

Представления board/views.py

Декоратор @login_required обеспечивает перенаправление на страницу входа/регистрации для неавторизованных посетителей. Функция def home(request) передает в шаблон index.html все существующие записи пользователя в удобном формате для сортировки задач по статусам.

Вся функциональность, связанная с регистрацией, авторизацией и выходом, реализована средствами Django и дополнительного модуля для управления формами django-crispy-forms. Crispy Forms обеспечивают автоматическую валидацию данных.

Дизайн для форм предоставляет модуль crispy-tailwind.

API

Реализация API на Django REST Framework выглядит максимально просто и лаконично:

  • Сериализаторы обеспечивают преобразование информации из нужных полей базы данных для использования на фронтенде и конвертируют получаемые с фронтенда данные для записи в базу.
  • Универсальные представления на основе классов ListTask и DetailTask предоставляют всю необходимую CRUD функциональность — создание, редактирование и удаление записей.
  • Фильтр owner=user в get_queryset(self) предоставляет пользователям доступ только к своим собственным записям.
  • Схемы SessionAuthentication и IsAuthenticated гарантируют, что операции с данными по API могут совершать только авторизованные пользователи.

Настройки settings.py

В INSTALLED_APPS необходимо указать формы crispy_forms
и набор стилей для них crispy_tailwind:

INSTALLED_APPS = [

'board.apps.BoardConfig',
'rest_framework',

'api.apps.ApiConfig',

'crispy_forms',

'crispy_tailwind',

]

Фронтенд

Клиентская часть приложения также в значительной мере полагается на встроенные возможности Django и его дополнительных модулей: django-crispy-forms, crispy-tailwind и messages. Фронтенд Канбана состоит из следующих шаблонов:

  • base.html — базовый шаблон с общими настройками для всех остальных страниц. Здесь подключаются Alpine.js, Axios, Tailwind и набор иконок Unicons.
  • index.html — главный шаблон, в котором содержится вся клиентская функциональность приложения.
  • login.html — вход на сайт.
  • messages.html — шаблоны для получения с бэкенда сообщений об успешных (и ошибочных) действиях пользователя.
  • register.html — регистрация на сайте.
  • settings.html — настройки пользовательского интерфейса (цветовая схема и фоновое изображение). Сведения об этих настройках хранятся в localStorage браузера

Шаблон index.html получает данные с бэкенда при загрузке страницы:

const tasksFromDjango = {{ tasks | safe }};

Alpine.js распределяет задачи по соответствующим колонкам:

Обращения к API для добавления, удаления и редактирования записей реализованы в addTask, removeTask и updateTask; перемещение задания в другую колонку — в onDrop(event, boardName).

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Развертывание приложения на сервере с ОС Ubuntu

Последовательность действий при развертывании готового проекта состоит из следующих шагов:

  • выбор конфигурации сервера, обновление ОС,
  • установка глобальных пакетов и модулей,
  • создание виртуального окружения,
  • клонирование репозитория проекта и установка локального ПО,
  • корректировка settings.py для продакшена,
  • создание базы данных и суперпользователя,
  • связывание Gunicorn с wsgi.py,
  • настройка конфигурации и запуск Gunicorn,
  • настройка и запуск обратного прокси Nginx,
  • получение сертификата Let’s Encrypt.

Рассмотрим эти шаги подробнее.

Конфигурация сервера

  • В панели управления Selectel откройте раздел «Облачная платформа», выберите «Серверы». Самый оптимальный вариант для развертывания нашего проекта — Shared Line:
  • Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  • Не забудьте выбрать опцию «Новый плавающий IP-адрес»: по этому адресу приложение будет доступно в интернете:
  • Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  • Конфигурация нашего сервера выглядит так:
  • Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Обновление ОС и установка глобального ПО

Начинаем работу с обновления Ubuntu и установки нужных пакетов:

sudo apt update

sudo apt install git ufw python3-pip python3-dev nginx

Создание виртуального окружения и клонирование репозитория с GitHub

Установим virtualenv:

sudo -H pip3 install —upgrade pip

sudo -H pip3 install virtualenv

Создадим директорию для проекта:

mkdir myproject

cd myproject

Создадим виртуальное окружение для проекта:

virtualenv myprojectenv

Активируем окружение:

source myprojectenv/bin/activate

В результате в начале командной строки будет отображаться (myprojectenv).

Теперь скопируем файлы проекта из GitHub-репозитория на сервер:

git clone https://github.com/natkaida/kanban.git

Установка Gunicorn и production-настройки

Перейдем в корневую директорию проекта, установим зависимости и Gunicorn:

cd kanban

pip install -r requirements.txt

pip install gunicorn

Создадим файл local_settings.py по этому примеру:

nano kanban/kanban/local_settings.py

Нужно убедиться, что значение DEBUG равно False, и прописать допустимые IP — локальный и внешний, в нашем случае это 95.213.229.177:

ALLOWED_HOSTS = ['95.213.229.177', 'localhost']

Кроме этого, нужно вставить соответствующее значение в SECRET_KEY, например:

SECRET_KEY = '!_u(2(^lpy&-2x$e%!k_u_gir0hg)q&5nurj00*gq0s4sseuav'

Теперь можно создать базу данных, сделать аккаунт администратора и собрать статические файлы в папку static:

python3 manage.py migrate

python3 manage.py createsuperuser

python3 manage.py collectstatic

Назначьте права для папки static:

chown www-data myproject/kanban/static

Добавьте порт 8000 в исключения фаервола:

sudo ufw allow 8000

Теперь можно запустить проект на собственном сервере Django:

python3 manage.py runserver 0.0.0.0:8000 —insecure

Параметр —insecure нужен для того, чтобы Django «увидел» статические файлы в папке static — после переключения статуса DEBUG на False он уже не занимается статикой по умолчанию. В дальнейшем работать со статическими файлами будет другой сервер. Мы установим его чуть позже. После запуска сервера сайт будет доступен по адресу http:// 95.213.229.177:8000:

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Для входа в панель администрирования достаточно добавить /admin – http:// 95.213.229.177:8000/admin:

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Подключение Gunicorn

Для работы Django-приложения в продакшене необходим надежный WSGI-сервер. В качестве такого сервера мы будем использовать Gunicorn:

cd myproject

gunicorn —bind 0.0.0.0:8000 kanban.wsgi

Перезапустим сервер:

python3 manage.py runserver 0.0.0.0:8000

Сайт должен быть доступен по тому же адресу http:// 95.213.229.177:8000. В случае ошибки проверьте, установлен ли Gunicorn в виртуальное окружение проекта myprojectenv. Если все работает корректно, остановите сервер (Ctrl + C) и деактивируйте виртуальное окружение командой deactivate.

Настройка конфигурации Gunicorn

Пока что нам приходилось запускать и останавливать сервер вручную. Но при наличии соответствующих конфигурационных файлов этот процесс можно полностью автоматизировать.

Нам понадобятся два файла: gunicorn.socket и gunicorn.service. Сначала создадим файл gunicorn.socket:

sudo nano /etc/systemd/system/gunicorn.socket

Его содержимое выглядит так:

[Unit]

Description=gunicorn socket

[Socket]

ListenStream=/run/gunicorn.sock

[Install]

WantedBy=sockets.target

Нажмите Ctrl + X и подтвердите сохранение.

Теперь с помощью команды sudo nano /etc/systemd/system/gunicorn.service создайте файл gunicorn.service:

[Unit]

Description=gunicorn daemon

Requires=gunicorn.socket

After=network.target

[Service]

User=root

WorkingDirectory=/root/myproject/kanban

ExecStart=/root/myproject/myprojectenv/bin/gunicorn —workers 5 —bind unix:/run/gunicorn.sock kanban.wsgi:application

[Install]

WantedBy=multi-user.target

Проверить файл gunicorn.service на наличие ошибок можно этой командой:

systemd-analyze verify gunicorn.service

Если при проверке оказалось, что путь к вашему gunicorn отличается от приведенного выше, то корректный путь к файлу можно найти, если активировать виртуальное окружение и выполнить команду which gunicorn. Если ошибок нет, можно активировать сервер:

sudo systemctl start gunicorn.socket

sudo systemctl enable gunicorn.socket

Проверим статус:

sudo systemctl status gunicorn.socket

  1. Статус корректно настроенного Gunicorn выглядит так:
  2. Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  3. В случае обнаружения ошибок, после их исправления нужно перезапустить Gunicorn, иначе он будет использовать предыдущую, ошибочную конфигурацию:

systemctl daemon-reload

Настройка Nginx

Перейдем к настройке Nginx. Создайте новый файл kanban без расширения:

sudo nano /etc/nginx/sites-available/kanban

В содержимом файла необходимо указать IP, по которому будет доступен сайт, порт и путь к директории со статическими файлами:

Читайте также:  Типы данных в Python

server {

listen 80;

server_name 95.213.229.177;

location = /favicon.ico { alias /myproject/kanban/static/favicon.ico }

location /static {

root /myproject/kanban/static;

}

location / {
include proxy_params;

proxy_pass http://unix:/run/gunicorn.sock;

}

}

Сохраните файл, а затем выполните приведенную ниже команду для создания символической ссылки:

sudo ln -s /etc/nginx/sites-available/kanban /etc/nginx/sites-enabled/

Чтобы проверить файл на наличие ошибок или опечаток, выполните команду:

sudo nginx -t

Если все в порядке, перезапустите Nginx:

sudo systemctl restart nginx

Осталось открыть порт 80:

sudo ufw delete allow 8000

sudo ufw allow 'Nginx Full'

Все готово — сайт доступен по адресу 95.213.229.177:

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Сертификат Let’s Encrypt

Для безопасной передачи данных на сайт нужно установить SSL-сертификат. Тогда сайт будет доступен по https. Однако получить сертификат можно лишь при наличии доменного имени. Для установки certbot выполните команду:

sudo apt-get install certbot python3-certbot-nginx

Затем запустите процедуру получения сертификата:

sudo certbot certonly —nginx

На этом этапе потребуется ввести адрес электронной почты и согласиться с условиями предоставления сертификата, после чего необходимо указать доменное имя сайта. Если указать просто IP, процедура прервется:

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Заключение

Деплой Django-приложения — непростая задача для начинающего разработчика.

Однако процесс развертывания становится интуитивно понятным, если представить себе схему взаимодействия Nginx, Django и Gunicorn: в этой связке Nginx выступает в качестве веб-сервера, обратного прокси-сервера и отвечает за выдачу статического контента, в то время как Gunicorn играет роль сервера приложений и прослойки между Nginx и Django. Nginx не способен запускать веб-приложения на Python и переводить запросы в WSGI, поэтому он передает HTTP-запросы Gunicorn, который, в свою очередь, отправляет их в Django для взаимодействия с ORM базы данных.

При использовании настроек, приведенных в статье, Nginx и Gunicorn будут идеально дополнять друг друга и обеспечат бесперебойную работу высоконагруженного Django-приложения.

Возможно, эти тексты тоже вас заинтересуют:

→ Недорогие механические клавиатуры: 5 вариантов, на которые стоит обратить внимание в 2023 году
→ Удар, еще удар: производство ОЗУ переживает не лучшие времена. Цены падают, производство сокращается
→ Еще есть куда падать: эксперты предрекают обвал поставок ПК на глобальном рынке в 2023 году. Причины и варианты решения

Анастасия Ербанова

How to Build a Notes app API using Django REST Framework and MongoDB | Engineering Education (EngEd) Program

MongoDB is a NoSQL database package. It keeps data in JSON-like format instead of the traditional row-column format. The Django REST framework is a robust package of tools for building extensible APIs. Django is one of the most well-liked packages that Python developers use to build websites.

You will learn how to use the powerful Django REST framework and MongoDB in your web projects. You will learn how to build CRUD features in a notes app.

In this article, you will:

  • Understand to integrate MongoDB into Django projects.
  • Learn how to set up and run Django REST API.
  • Create CRUD features in Django REST API.
  • Build a Notes app API.

Prerequisites

To follow this article along it is important to have the following:

Setting up the MongoDB server

You may download and install the MongoDB database server from the official MongoDB website.

You can check this guide if you use a Windows machine, Installing MongoDB on Windows.

For Linux users, follow this tutorial, How to Install MongoDB on Ubuntu 20.04.

  • Mac users can follow the tutorial, Installing MongoDB on Mac
  • You can check the version of MongoDB installed on your machine with the following command:
  • To use the mongo shell, start the service with the following command:
  • Create and switch to a new database with the following command:

MongoDB Compass is a GUI tool that enables you to interact with MongoDB. You can view and operate your MongoDB databases with MongoDB Compass.

MongoDB Compass is available for download on the official website, Download and Install Compass.

Setting up the virtual environment

We will install virtualenv to enable a virtual environment for our project. It will enable one to isolate a project and its dependencies from other projects on your machine.

Run the following command to install virtualenv:

python -m pip install —user virtualenv

Next, let’s create a folder for our project and then create a virtual environment inside it.

Create a folder called django_mongodb_project as such:

mkdir django_mongodb_project

Move into the project folder with the following command:

cd django_mongodb_project

  1. Create a virtual environment called venv with the following command:
  2. Next, activate the environment:
  3. If you use Windows, activate the virtual environment with the following command:

Install packages

We will need the django, djangorestframework, and djongo packages.

  • django: the Django framework package.
  • djangorestframework: the Django REST Framework for developing APIs in Django.
  • djongo: a tool that maps Python objects to MongoDB documents.

Let’s install Django and the Django REST framework with the following command:

pip install django django-rest-framework djongo

Now, create a Django project called notes_app:

django-admin startproject notes_app
cd notes_app

Then, create an app called api inside the notes_app project.

django-admin startapp api

Navigate to the settings.py file inside the project-level folder. Then, change the INSTALLED_APPS list by adding our created app, api and rest_framework:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api',
]

Configuring MongoDB

Navigate to the settings.py file and change the DATABASES setting as follows:

DATABASES = {
'default' : {
'ENGINE' : 'djongo',
'NAME' : 'notes_database'
}
}

Building the notes app via API

We will develop an API for a notes app to jot and take notes down. Users will be able to take notes, get a list of notes they made, and delete the notes.

Let’s define a model for the notes in the models.py file of the api app that we have created:

from django.db import models
class Note(models.Model):
title = models.CharField(max_length=50)
text = models.TextField()
def __str__(self):
return self.title

Let’s migrate the model into the database:

python manage.py makemigrations
python manage.py migrate

Next, let’s create a serializer class. When users make requests to the API, the serializers format the corresponding responses. Create a new serializers.py file in the api app folder. Make the necessary imports as demonstrated below and create the NoteSerializer class.

from rest_framework import serializers
from .models import Note
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Note
fields = ('id', 'title', 'text')

Next, let’s create the views that will handle the request and response actions of our API. Create the NoteList and NoteDetail views in the views.py file of the api app.

from rest_framework import generics
from .models import Note
from .serializers import NoteSerializer
class NoteList(generics.ListCreateAPIView):
queryset = Note.objects.all()
serializer_class = NoteSerializer
class NoteDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Note.objects.all()
serializer_class = NoteSerializer

In the code above, we created two views. NoteList enables us to create a note and also view a list of created notes. NoteDetail allows us to view a particular note, update or delete it.

Next, we will create endpoints to receive requests. Create a new urls.py file inside the api directory.

Create the urlpatterns as follows inside:

from django.urls import path
from api import views
urlpatterns = [
path('', views.NoteList.as_view()),
path('/', views.NoteDetail.as_view()),

Next, set up the urls.py file of the project to point to the app level urlpatterns. Then, include a path to the urls.py file of the api app.

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')), # add this line
]

The first endpoint receives the actions ‘LIST’ and ‘CREATE’ actions of the NoteList view. The second endpoint takes the id of a particular note to view the details of the note.

Testing with browsable API

Django REST framework comes shipped with the browsable API. You can test your API endpoints with the browsable API.

Читайте также:  Лучшие практики Golang: путь к чистому коду

Activate the test server:

python manage.py runserver

Then navigate to 127.0.0.1:8000/api/ on your browser to create notes.

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

You can add notes and refresh the webpage to see the added notes.

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Then, view the created notes at 127.0.0.1:8000/api/id:

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

You can also delete or update the note on the detail page. The red square in the next image contains the delete button.

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

You can also update the title or text of the note. See the blue square area on the image above. Edit the text or title and click the ‘PUT` button.

Conclusion

This article described how to configure the MongoDB database for a RESTful Django API. We also created an API for a Notes app. You may go on and use MongoDB in your Django REST API projects.’

  • You may check out the example code in the GitHub repo.
  • Thanks for reading.
  • Happy coding!
  • Peer Review Contributions by: Geoffrey Mungai

Django Note Taking App With Source Code

A Django Notes App users should be able to see or modify other users’ posts (in case this application gets deployed on a web browser or web framework), this Django Note app can be easily converted between a blog and a note-taking app.

This Note App In Django also includes a downloadable Project With Source Code for free, just find the downloadable source code below and click to start downloading.

Read or Visit the other programming languages used in notes app

To start creating a Django Note App, makes sure that you have PyCharm Professional IDE or any platform of django and its requirements Installed in your computer.

About ProjectProject Details
Project Name Note Taking App Django
Python version (Recommended) 3.8 Version
Programming Language Used Python Django Language
Developer Name itsourcecode.com
IDE Tool (Recommended) Sublime, Visual Studio, PyCharm
Project Type Web Application
Database SQLite

Django Note App Overview

To perform this python django project make sure that you have knowledge in the following:

  • CSS
  • HTML
  • Javascript
  • Database Management
  • Create a file note
  • Read Note
  • Update Note
  • Delete documents Note
  • User Login/Logout
  • User Registration
  • django_project – In this method Which is the main method of the app.
  • blog – In this method which is the main feature of the app.
  • media – In this method which you can found all the media that being upload in this app.
  • users – In this method which is the users that manage the app.

Time needed: 5 minutes

Here are the steps on how to create a Note Taking App in Django With Source Code

  • Step 1: Open file.First , open “pycharm professional” after that click “file” and click “new project“.
  • Step 2: Choose Django.Second, after click “new project“, choose “Django” and click.Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  • Step 3: Select file location.Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  • Step 4: Create application name.Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js
  • Step 5: Click create.Fifth, finish creating project by clicking “create” button.
  • Step 6: Start of coding.you are free to copy the following codes below in the given modules and method required.

Build a modern web app using Django and Javascript with no build tools

{# content goes here #}
{% block content %}{% endblock %}

{% block footer_js %}

{% endblock %}

Notes

  • — this section includes TailwindCSS ,(styling) DaisyUI (pre-made UI components) AlpineJS required. In production, these files should be minified, in the next article, we will look at how to improve this setup and make it production ready.

  • const csrftoken
    — add the csrftoken to the page, this will be required for Ajax requests to the backend

  • const client = SwaggerClient('/api/schema/',..
    — set up a swagger-js client . This is a nice addition that will make interacting with the backend API more convenient.

  • agger is an open-source toolset that is centered around the OpenAPI Specification (OAS).

More on Swagger

Swagger is an open-source toolset that is centered around the OpenAPI specification or “OAS”.

OAS defines a standard, language-agnostic interface for both humans and computers to understand a service without access to source code.

Swagger provides tools that can interact with this specification such as

  • Swagger Codegen for generating server stubs, and client SDKs.
  • Swagger Editor for designing APIs with the OpenAPI spec
  • Swagger UI for visualizing & interacting with the OpenAPI specs.

In the next tutorial, we will look at Swagger in more detail.

Create the home page template

The landing page extends the base.html template and only includes one, plain html header component. We expect this page to be static over time.

templates/home.html

{% extends 'base.html' %}

{% block content %}
{% include «components/header.html» %}
{% endblock %}

config/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page

urlpatterns = [
path(«admin/», admin.site.urls),
path(«», cache_page(60 * 15)(TemplateView.as_view(template_name=»home.html»)), name=»home»),
]

Notes

  • templates/home.html
    — our landing page only includes a header components/header.html section, for now, you can easily extend this to add a footer. For this article, we used an online tailwind page builder. You can use a ton of resources to build high-quality landing pages fast, for example, shuffle.dev , devdojo , and many more.

  • config/urls.py
    — uses a simple Django
    TemplateView
    defined directly in
    config/urls.py
    . You will note we have added
    cache_page
    to avoid dynamically generating the page every time a request is made.

Views, Models, and API

In this next step, we will set up a dashboard view and required api endpoints.

What we want to achieve:

  • use traditional Django templates to initially render the main dashboard landing.html page
  • include any additional data in the page context to avoid having to make extra API calls from the frontend
  • setup api endpoints for the Todo app

Create the model

apps/dashboard/models.py

from django.db import models
from django.utils import timezone

class TodoManager(models.Manager):
def to_list(self):
return [todo.to_json() for todo in self.get_queryset()]

class Todo(models.Model):
STATUS_CHOICES = [
(«done», «done»),
(«outstanding», «outstanding»),
]
detail = models.CharField(max_length=500)
created = models.DateField(default=timezone.now, null=False)
status = models.CharField(
max_length=100, null=True, blank=True, choices=STATUS_CHOICES
)
updated = models.DateField(default=timezone.now, null=False)

objects = TodoManager()

def to_json(self):

return {
«id»: self.id,
«created»: self.created.strftime(«%Y-%m-%d»),
«detail»: self.detail,
«status»: self.status,
}

Notes:

  • TodoManager
    — extend manager to include business logic for our todos app in this case returns a list of formatted todos.

  • def to_json(self)
    : — added a convenience method to format our todos for the front end.

Create the views and API

Next, we will create our template view for the dashboard landing page.

apps/dashboard/views.py

from django.utils import timezone
from django.views.generic import TemplateView

class DashboardView(TemplateView):

template_name=»dashboard/landing.html»

def get_context_data(self, **kwargs):

context = super().get_context_data(**kwargs)
context.update({«chart_data»: self.get_chart_data()})
return context

def get_chart_data(self):
«»»return chart data»»»
return [
{«value»: 335, «name»: «Direct»},
{«value»: 310, «name»: «Email»},
{«value»: 274, «name»: «Union Ads»},
{«value»: 235, «name»: «Video Ads»},
{«value»: 400, «name»: «Search Engine»},
]

Notes

  • DashboardView
    — we modified the
    get_context_data
    method to add additional data to the Chart. This is embedded in the page context and saves us from having to make an extra API call on the frontend Chart App to fetch this data.

Let's add our backend API. We are using the Django Ninja library as a replacement for the excellent Django rest framework library. The library uses Pydantic for data validation, and has async and type hints support.

apps/dashboard/schema.py

from typing import Optional
from datetime import datetime
from django.utils import timezone

from ninja import ModelSchema
from .models import Todo

class TodoSchema(ModelSchema):

created: Optional[datetime] = timezone.now()
status: Optional[str] = «outstanding»

class Config:
model = Todo
model_fields = [«id», «detail», «created», «status»]

Notes:

  • TodoSchema
    — the schema serializes (converts data to python types) and deserializes data (converts data to content types such as JSON or XML). This is the equivalent of a serializer class in the Django rest framework.

apps/dashboard/api.py

from ninja import Router
from .models import Todo
from .schema import TodoSchema

router = Router(tags=[«todos»])

@router.get(«/», operation_id=»getTodos»)
def list_todos(request):
«»»List todos»»»
todos = Todo.objects.to_list()
return todos

@router.get(«/{todo_id}», operation_id=»getTodo»)
def todo_details(request, todo_id: int):
«»»Retrive todo»»»
todo = Todo.objects.get(id=todo_id)
return todo.to_json()

@router.delete(«/{todo_id}», operation_id=»deleteTodo»)
def delete_todo(request, todo_id: int):
«»»Delete todo»»»
obj = Todo.objects.filter(id=todo_id).first()
if obj is not None:
obj.delete()
return {«message»: f»deleted to with id {todo_id}»}

return router.create_response(
request,
{«message»: «Delete failed obj not found»},
status=404,
)

@router.post(«/», operation_id=»addTodo»)
def post_todo(request, payload: TodoSchema):
«»»Add todo»»»
obj = Todo.objects.create(detail=payload.detail, status=payload.status)
obj.save()
return obj.to_json()

Notes:

  • router
    — we created the todos router and added the tag 'todos'. This will ensure the correct tag is included in our api docs view. We will refer back to this file when we wire up the routers and urls below.

  • added all the endpoints required to perform basic crud operations. You will notice that on the
    post_todo
    endpoint the payload should adhere TodoSchema data type. If you need more guidance on this, check out the Django ninja docs .

Wire up the routers and URLs

In this section, we will wire up the
DashboardView
and
api
endpoints to our URL configuration.

apps/dashboard/urls.py

from django.urls import path

from . import views

app_name = «dashboard»
urlpatterns = [
path(
«dashboard/»,
views.DashboardView.as_view(),
name=»landing»,
),
]

apps/config/api.py

from ninja import NinjaAPI
from apps.dashboard.api import router as todos_router

api = NinjaAPI()

api.add_router(«/todos/», todos_router)

apps/config/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page

from .api import api

urlpatterns = [
path(«admin/», admin.site.urls),
path(«», cache_page(60 * 15)(TemplateView.as_view(template_name=»home.html»)), name=»home»),
path(«», include(«apps.dashboard.urls»)),
path(«api/», api.urls),
]

Notes:

apps/dashboard/urls.py
— we added the
DashboardView
to the dashboard URL configuration file.

apps/config/api.py
— imported the todos router we created earlier and added it to our API.

apps/config/urls.py
— updated the main urls.py to include the dashboard app URL config and API endpoints.

The landing page and API docs should now be live. This UI is automatically generated by Swagger.

Приложение для хранения заметок на Django, Django Ninja REST Framework и Alpine.js

Create the dashboard templates and alpine component

Next, we will create the templates for the dashboard landing page, as well as the dashboard javascript component.

Summary of the workflow

  • creates the dashboard layout template
  • add the landing page, and include AlpineJS attributes directly in the markup but do not inline javascript directly on the page.
  • create the templates for the Chart app and Todo app

Creating the dashboard layout and landing page templates

templates/layout.html

{% extends 'base.html' %}
{% block content %}

{% block dashboard_content %}{% endblock %}

{% endblock content %}

Notes:

  • this is a normal Django template that extends
    base.html
    the template and includes a dashboard navbar which should appear on every dashboard page.

templates/landing.html

{% extends 'dashboard/layout.html' %}{% load static %} {% block dashboard_content %}

  • Dashboard

Back

{% include «dashboard/components/charts.html» %}

{% include «dashboard/components/todo.html» %}

{% endblock %}

{% block footer_js %}
{{ block.

super }}

{# load any variables required by our scripts that have to be rendered using django templates #}

{{chart_data|json_script:»chartData»}} {# backend provided json data#}

{% endblock %}

Notes:

There is a lot going on here, let's break down the important bits

  • x-data='dashboard()'
    — Alpine directive that defines a chunk of HTML as an Alpine component. Properties defined in the dashboard Alpine component will be available to all the element children. The alpine component itself is included on the page using this line

    , we will compose it later.

  • @click=»changeView('index')»
    — @ is a shortcut for the alpine x-bind: directive. In this case, it binds the click event to the
    changeView
    a function defined in the dashboard component.

  • x-show=»activeView.key !== 'index'»
    — x-show provides an expressive way to hide or show DOM elements. On this page, it will hide or show the index view, chart app view, or todo app view depending on what the
    activeView
    variable is set to.

  • x-cloak
    — to avoid the incorrect view showing before alpine loads, we add the x-cloak direct to each of the views. In our static/styles/site.css file, we also add the required CSS for this to work
    [x-cloak] { display: none !important; }

  • — this section is to show the correct app icon. We use the x-for directive to create DOM elements by iterating through a list. This is an example of client-side javascript rendering HTML.

  • {{chart_data|json_script:»chartData»}}
    — in the DashboardView we included chart_data in the page context. This json_script template tag will transform the Python object as JSON wrapped in a script tag which can be consumed by javascript.

  • const listIconUrl = «{% static «icons/list.svg» %}»
    — we also include URLs for our app icons. These will be used in the alpine dashboard component. We are defining them before we import our page js files so that they are available when Alpine loads the component.

At this stage, we have defined the templates but not the Alpine component. Therefore, only the header will be rendered if we visit http://localhost:8000/dashboard/

Other required templates

You can refer to the template/dashboard/components in the codebase for the
todo.html
,
chart.html
and
todo_form.html
template files.

todo_form.html

Notes:

x-model
— one thing to note here is the use of the
x-model
directive, which binds the value of the textarea to Alpine data. There are no other new concepts in these templates that we have not covered above.

Creating the dashboard Alpine Component

This is our client side javascript application. It will handle the routing for the Todo, Chart and dashboard landing views as well as logic required for data fetching etc.

static/js/dashboard.js

django-ninja,natkaida

View Code? Open in Web Editor
NEW

9.0
9.0
0.0
25 KB

Гибридное приложение для хранения заметок на Django, Django Ninja API и Alpine.js

Python 59.69%
HTML 37.14%
CSS 3.17%

alpine-js
alpinejs
axios
django-ninja
django-rest-framework

  • A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • ???? Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • An Open Source Machine Learning Framework for Everyone

  • The Web framework for perfectionists with deadlines.

  • A PHP framework for web artisans

  • Bring data to life with SVG, Canvas and HTML. ????????????

  • JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • Some thing interesting about web. New door for the world.

  • A server is a program made to process requests and deliver data to clients.

  • Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Some thing interesting about visualization, use data art

  • Some thing interesting about game, make everyone happy.

  • We are working to build community through open source technology. NB: members must have two-factor auth.

  • Open source projects and samples from Microsoft.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *