Git Product home page Git Product logo

django's Introduction

fands.dev django template

Shields.io

Easy peasy

What is in the box

  • API-only django (checkout this post in Russian) based on Django REST Framework with JWT support.
  • poetry with separate development-time dependencies.
  • Strict type checking with mypy, django-stubs and djangorestframework-stubs.
  • tons of linters and formatters (contact us if any interesting linter is not included, see Makefile fmt, lint commands).
  • Starter CI configuration on GitHub Actions.
  • pytest with useful stuff like freezegun, pytest-mock and super convinient [DRF test client](https://github.com/fandsdev/django/blob/master/{{ cookiecutter.name }}/src/app/testing/api.py).
  • Custom user model.
  • drf-spectacular for API Schema generation.
  • django-axes for additional security.
  • Whitenoise for effortless static files hosting.
  • Cloudflare ready with django-ipware.
  • Sentry. Set SENTRY_DSN env var if you need it.
  • Postgres.

Installation

You need python 3.11, poetry and cookiecutter.

We only support PostgreSQL as the database backend, so make sure it runs on localhost:5432 before installing the project.

pipx install poetry
pipx install cookiecutter

cookiecutter gh:fandsdev/django

FAQ

I wanna hack this!

Thank you so much! Check out our build pipeline and pick any free issue.

django's People

Contributors

42juododranoel avatar alexanderavrov avatar denissurkov avatar dependabot-preview[bot] avatar dependabot[bot] avatar e-stepanov avatar f213 avatar hnthh avatar inerv avatar kazqvaizer avatar nitrok avatar nkiryanov avatar nvo87 avatar renovate[bot] avatar tezlaa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

django's Issues

Random username issues

Иногда mixer.blend('users.User') падаёт из-за того, что не может сгенерить уникальный юзернейм. Надо починить это, к примеру как тут

Сделать, чтобы в сгенерённом проекте работал healthcheck

Сейчас мы не добавляем healthcheck в итоговый проект, потому что указываем в нём HTTP HOST. Нужно решить эту проблему — к примеру сделать так, чтобы итоговая джанга не требовала правильного хоста — в 2024 году это не актуально.

Issue with Installing on a local machine

From created Readme.txt

Install requirements:

pip install pip-tools
cd src && pip-sync requirements.txt dev-requirements.txt
cp app/.env.ci app/.env  # default environment variables

actual result: requirements are not set

➜  f213 pip install --upgrade pip-tools
<skipped>
➜  f213 pip show pip-tools
Name: pip-tools
Version: 5.1.1
...
Location: /usr/local/lib/python3.7/site-packages
...
➜  f213 pwd
<skipped>/f213
➜  f213 ll
total 136
drwxr-xr-x@ 18 o  staff   576B Apr 29 13:57 .
drwxr-xr-x@  4 o  staff   128B Apr 29 14:43 ..
drwxr-xr-x@  3 o  staff    96B Apr 29 13:29 .circleci
-rw-r--r--   1 o  staff    48B Apr 29 13:04 .dockerignore
-rw-r--r--   1 o  staff   269B Apr 29 13:04 .editorconfig
-rw-r--r--   1 o  staff   158B Apr 29 13:04 .flake8
-rw-r--r--   1 o  staff   1.6K Apr 29 13:04 .gitignore
drwxr-xr-x@  8 o  staff   256B Apr 29 13:58 .idea
-rw-r--r--   1 o  staff   120B Apr 29 13:04 .isort.cfg
-rw-r--r--   1 o  staff   1.8K Apr 29 13:04 Dockerfile
-rw-r--r--   1 o  staff   2.9K Apr 29 13:04 README.md
-rw-r--r--   1 o  staff   377B Apr 29 13:04 dev-requirements.in
-rw-r--r--@  1 o  staff    13K Apr 29 13:05 dev-requirements.txt
-rw-r--r--   1 o  staff   159B Apr 29 13:04 requirements.in
-rw-r--r--@  1 o  staff   8.6K Apr 29 13:04 requirements.txt
drwxr-xr-x@ 11 o  staff   352B Apr 29 13:37 src
-rwxr-xr-x   1 o  staff   235B Apr 29 13:04 update-deps.sh
drwxr-xr-x@  7 o  staff   224B Apr 29 13:39 venv
➜  f213 cd src && pip-sync requirements.txt dev-requirements.txt
Usage: pip-sync [OPTIONS] [SRC_FILES]...
Try "pip-sync --help" for help.

Error: Invalid value for "[SRC_FILES]...": Path "requirements.txt" does not exist.

Эксперимент: использовать официальные образы Postgres и redis вместо alpine

Обычно в билдах запуск контейнеров с постгресом у нас занимает по 20 секунд. Есть гипотеза, что если мы будем использовать более популярные образы, типа postgres:16 вместо postgrtes:16-alpine, то этот процесс ускорится, потому что кеш этих образов с большей вероятностью окажется на воркере.

Это пока только гипотеза, я сам не проверял.

Добавить недостающие фабрики в FactoryProtocol

Привет!

У нас есть FactoryProtocol. Он помогает при тайпинге в фикстурах.

На старте проекта у нас уже есть какие-то фабрики. К примеру, user.

Эти фабрики сейчас не добавлены в FactoryProtocol. Хочется, чтобы они были уже на старте проекта. Мелочь, но приятно.

Добавить post_act в BaseService

Иногда в сервисах нужно использовать transaction.atomic

При этом некоторые действия можно будет сделать только после того, как будет выполнена основная часть сервиса.

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

Если вызывать таску внутри тела транзакции, то таски будут отваливаться, потому что юзера еще нет в системе (или вообще не будет, потому что транзакция не прошла).

Я предлагаю два варианта:

  1. Сделать отдельный сервис BaseTransactionService
class BaseTransactionService(BaseService):
    def act(self):
        with transaction.atomic():
            result = self.transactional_act()
        self.apply_after_transaction()
        return result

    @abc.abstractmethod
    def transactional_act(self):
        ...

    def apply_after_transaction(self):
        ...
  1. Добавить в базовый сервис post_act
...
    def __call__(self) -> None:
        self.validate()
        result = self.act()
        self.post_act()
        return result
...

На мой взгляд, первый способ лучше. По названию метода сразу понятно, что действие будет внутри транзакции. Но тут хочу мнения со стороны.

Fix deprecation warnings in django-healthcheks

This ones:

app/tests/tests_health.py::test
  /Users/f213/prj/f213-django-boilerplate/testing/django/venv/lib/python3.7/site-packages/django_healthchecks/urls.py:6: RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path().
    url(r'^$', views.HealthCheckView.as_view(), name='index'),

app/tests/tests_health.py::test
  /Users/f213/prj/f213-django-boilerplate/testing/django/venv/lib/python3.7/site-packages/django_healthchecks/urls.py:8: RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path().
    name='service'),

Обновить на Django >= 4.0 & python3.10

Во внутренних проектах используется python3.10. Предлагаю зафиксировать это в readme.md.

Django 4.0 спорный момент. Я пока не трогал асинхронную джангу. Но если джанга движется туда, а значит это тренд.

https://www.djangoproject.com/weblog/2021/dec/07/django-40-released/
https://docs.djangoproject.com/en/4.1/topics/async/

@f213 , @kazqvaizer , @nvo87 , @e-stepanov, что думаете о Django 4?

Make sepulkas app optional

Having a real example of app is cool.
But I think this app should be optional or just as example in the repository. Otherwise it's inconvenient to remove it after creating new project via cookiecutter

FIx editor config max_line_length

@f213 , почему в .editorconfig max_line_length стоит 0?

Из-за этого в IDE появляется отвратительная линия в начале строк. Конечно, её можно отключить, но она визуально показывает ограничение.

Пример линии, как сейчас настроен editorconfig:
image

Пример линии, как должно быть -- она сбоку:
(ограничение 160 символов для .py файлов)
image

Flake8 test failed

I have faced issue with flake8 tests in post gen hook.

Steps to reproduce:

test % docker run -ti -v $PWD:/app -w /app python:3.8 bash
root@728b016278ec:/app# ls
root@728b016278ec:/app# pip install --upgrade cookiecutter
root@728b016278ec:/app# cookiecutter gh:f213/django
project_slug [django]: test

The error:

Running flake8..
./app/models.py:3:1: I004 isort found an unexpected blank line in imports
./app/asgi.py:11:1: I004 isort found an unexpected blank line in imports
./app/pagination.py:2:1: I004 isort found an unexpected blank line in imports
./app/pagination.py:3:1: I001 isort found an import in the wrong position
./app/wsgi.py:11:1: I004 isort found an unexpected blank line in imports
./app/admin/__init__.py:1:1: I003 isort expected 1 blank line in imports, found 0
./app/admin/__init__.py:2:1: I001 isort found an import in the wrong position
./app/management/commands/makemigrations.py:2:1: I004 isort found an unexpected blank line in imports
./users/admin.py:3:1: I003 isort expected 1 blank line in imports, found 0
./users/urls.py:2:1: I003 isort expected 1 blank line in imports, found 0
ERROR: Stopping generation because post_gen_project hook script didn't exit successfully
Hook script failed (exit status: 1)

Gist logs: https://gist.github.com/teke97/557231333e9d715087cfe690575e6ede
Tested with docker images python:3.8, python:3.7 and python:3.9 (same result).

Getting started guide for the newbies

Something like this:

1. create a VM
2. sudo apt install libsqlite3-dev libffi-dev zlib1g-dev
3. создал пользователя runner
4. установил pyenv
5. pyenv init
6. pyenv install 3.8.5
7. pyenv local 3.8.5
8. pip install virtualenv
9. python -m venv ./ap
10. source ap/bin/activate
11. pip install --upgrade cookiecutter
12. cookiecutter gh:f213/django

Добавить admin_notice

django-admin-notice добавляет плашку на админку сайта. Лучше вынести сразу все три переменные в энв.

изображение

Как по мне, мелочь, но приятно.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Location: renovate.json
Error type: The renovate configuration file contains some invalid settings
Message: The "poetry" object can only be configured at the top level of a config but was found inside "packageRules[0]"

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

None detected


  • Check this box to trigger a request for Renovate to run again on this repository

Error during building project with "cookiecutter gh:fandsdev/django" command

# The following packages are considered to be unsafe in a requirements file:
# setuptools
pip-sync requirements.txt dev-requirements.txt
Incompatible requirements found: packaging==23.0 (from -r dev-requirements.txt (line 229)) and packaging==21.3 (from -r requirements.txt (line 76))
make: *** [install-dev-deps] Error 2
ERROR: Stopping generation because post_gen_project hook script didn't exit successfully
Hook script failed (exit status: 2)

app/api/viewsets пустой

файл app/api/viewsets.py с дефолтными viewsets стал пустым после этого коммита. Либо это ошибка, либо нужно изменить файл с темплейтом который ссылается на модель DefaultModelViewSet из этого фалйа

Add dotenv-linter

Cuz we encourage using of Django-environ, we should add linting of .env files to to generated project CI configuration.

Error on project creation

Unable to create file 'src/app/.env.ci error

➜  f213 cookiecutter --version
Cookiecutter 1.6.0 from /usr/local/lib/python3.7/site-packages (Python 3.7)
➜  f213 cookiecutter gh:f213/django
You've downloaded /Users/o/.cookiecutters/django before. Is it okay to delete and re-download it? [yes]: yes
project_slug [django]: f213
Unable to create file 'src/app/.env.ci'
Error message: 'random_ascii_string' is undefined
Context: {
    "cookiecutter": {
        "_copy_without_render": [
            ".circleci/config.yml"
        ],
        "_template": "gh:f213/django",
        "project_slug": "f213"
    }
}
➜  f213

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.