Welcome to Django Base’s documentation!¶
Django Base¶
Documentation¶
The full documentation is at http://django-base.readthedocs.io.
Live demo @ http://django-base.104.236.104.21.xip.io
Quickstart¶
- Clone o repositório.
- Crie um virutalenv com o Python 3.5
- Ative o Virtualenv.
- Instale as dependencias.
5. Configure as variaveis sensiveis do projeto com o .env 5. Configure as variaveis referentes ao dokku no arquivo deploy_utlis/.env 6. Migre seus modelos para o Banco de Dados 7. Roda o collectstatic para configurar arquivos staticos 8. Execute os testes.
Digite no terminal:
git clone https://github.com/tyagow/django-base.git Nome-Do-Projeto
cd Nome-Do-Projeto
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp contrib/env-sample .env
cp contrib/env-d0kku-sample deploy_utlis/.env
python manage.py collectstatic
python manage.py migrate
python manage.py test
python manage.py runserver
Como fazer o Deploy?¶
Features¶
- Django 1.10.5
- Bootstrap 4 alpha 6
- JQuery 3.1.1
- Python Decouple
- DJ Static (serving static files locally)
- Dj Database URL
- Django test without migrations
- Django Crispy Forms
- Django bootstrap3
- Social User Login App* (facebook e twitter)
- Django Extensions
- Dokku pre configured
- Multi languange i18n
- Coverage
Need additional configuration
Translation¶
Running Tests¶
Does the code actually work?
source .venv/bin/activate
(myenv) $ python manage.py test
Installation¶
- Clone o repositório.
- Crie um virutalenv com o Python 3.5
- Ative o Virtualenv.
- Instale as dependencias.
- Configure a instancia com o .env
- Migre seus modelos para o Banco de Dados
- Roda o collectstatic para configurar arquivos staticos
- Execute os testes.
Digite no terminal:
git clone https://github.com/tyagow/django-base.git Nome-Do-Projeto
cd Nome-Do-Projeto
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp contrib/env-sample .env
python manage.py collectstatic
python manage.py migrate
python manage.py test
python manage.py runserver
Usage¶
Translation¶
Complilar textos a serem traduzidos
Criar uma pasta locale dentro de cada App que será traduzido.
Criar arquivo para as mensagens a serem traduzidas:
django-admin makemessages -l en
*O ultimo parametro é referente a linguagem que o arquivo será traduzida
Traduzir o arquivo django.po
Compliar arquivo traduzido:
django-admin compilemessages
NOTES
- Não traduzir palavras dentro de {} pois são variáveis usadas pelo django e não texto a ser traduzido.
Pagination¶
Pode usar parametros como filtros que os links da paginação irão redirecionar para a pagina certa com o link dos filtros ativos.
Na view:
parametros = ''
for item, value in request.GET.dict().items():
if not item == 'page':
parametros += '&{}={}'.format(item, value)
parametros = parametros.replace(' ', '+')
paginator = Paginator(queryset_list, PAGINACAO_QUANTIDADE_POR_PAGINA)
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
[...]
context['parametros'] = parametros
return render(request, [...])
No template:
{% include 'widgets/pagination.html' with object_list=query_list pagination_section='#section_target' %}
Criar o arquivo widgets/pagination.html na pasta templates com o seguinte conteudo:
<div class="row">
{% if object_list.paginator.num_pages > 1 %}
<ul class="pagination">
{% with ''|center:object_list.paginator.num_pages as range %}
{% for _ in range %}
<li{% if forloop.counter == object_list.number %} class="active"{% endif %}><a href="?page={{ forloop.counter }}{{ parametros }}{{ pagination_section }}">{{ forloop.counter }}</a></li>
{% endfor %}
{% endwith %}
</ul>
{% endif %}
</div>
Como fazer o Deploy?¶
- Install Digital Ocean Dokku image
- Send your ssh-key to dokku
- Connect via ssh to your server
- Create app in dokku
- Install postgres plugin in dokku
- Create database for your app in dokku
- Link database and app in dokku
- Set DEBUG in dokku
- Generate new SECRET_KEY
- Set SECRET_KEY in dokku
- Set ALLOWED_HOSTS in dokku
- Set Global Domain dor dokku
- Push your code to dokku
- Run the migrations
- Collect static data with DEBUG=False
Digite no terminal
(local) cat ~/.ssh/id_rsa.pub | ssh root@<your.ip.address> "sudo sshcommand acl-add dokku [description]"
(local) ssh root@<your.ip.address>
(server) dokku apps:create <app-name>
(server) sudo dokku plugin:install https://github.com/dokku/dokku-postgres.git
(server) dokku postgres:create <database-name>
(server) dokku postgres:link <databse-name> <app-name>
(local) git remote add dokku dokku@dokku.me:<app-name>
(local) ssh dokku@<your.ip.address> config:set <app-name> DEBUG=False
(local) python contrib/secret_gen.py
(local) ssh dokku@<your.ip.address> config:set <app-name> SECRET_KEY='<new-generated-key>'
(local) ssh dokku@<your.ip.address> config:set <app-name> ALLOWED_HOSTS=<app-name>.<your.ip.address>.xip.io
(local) ssh dokku@<your.ip.address> config:set <app-name> AWS_STORAGE_BUCKET_NAME=XXXXXXXXXXX AWS_ACCESS_KEY_ID=XXXXXXXXXXX AWS_SECRET_ACCESS_KEY=XXXXXXXXXXX
(local) ssh dokku@<your.ip.address> domains:add-global <your.ip.address>.xip.io
(local) ssh dokku@<your.ip.address> domains:enable <app-name>
(local) git push dokku master
(local) ssh dokku@<your.ip.address> run <app-name> python manage.py migrate
(local) DEBUG=False python manage.py collectstatic
Note
- Depois do primeiro deploy feito basta um comando para o deploy:
git push dokku master
- Não esquecer de migrar/atualizar o banco de dados sempre que alterar um modelo:
ssh dokku@<your.ip.address> run <app-name> python manage.py migrate
Dokku¶
- Change PORT
` (não recomendado, se configurar na porta 80 só poderei ter 1 serviço (app) ) ” you can only bind a single service to port 80 if you do not use a vhost but i highly suggest using a vhost for your server so then you get urls like app.vhost.com ” @ savant`
` dokku config:set APP DOKKU_NGINX_PORT=80 DOKKU_PROXY_PORT_MAP=http:80:5000 `
- Configurar um vhost
dokku domains:add-global domain_here
- Re-enable vhosts for your app
( http://dokku.viewdocs.io/dokku/configuration/domains/ )
dokku domains:enable APP
- Server < 1 GB RAM
- http://dokku.viewdocs.io/dokku/getting-started/advanced-installation/#vms-with-less-than-1gb-of-memory
Run on server:
cd /var
touch swap.img
chmod 600 swap.img
dd if=/dev/zero of=/var/swap.img bs=1024k count=1000
mkswap /var/swap.img
swapon /var/swap.img
free
echo "/var/swap.img none swap sw 0 0" >> /etc/fstab
Configurar AmazonS3¶
Circle-ci Automatic Deploy to Dokku¶
- Generate new ssh-key without password - Give a name to the file.
- Copy new ssh-key.pub to your project (you must be in your root project)
- Add ssh-key private to circle-ci in circle-ci website
- Edit circle.yml
- add ssh-key to dokku server (go to add-ssh-to-dokku section)
Terminal:
$ ssh-keygen -t rsa
$ cp ~/.ssh/<ssh-key>.pub ./deploy_utils/deploy_key
$ circle.yml ->
machine:
python:
version: 3.5.1
general:
artifacts:
- "htmlcov"
dependencies:
pre:
- cp contrib/env-sample .env
test:
override:
- coverage run manage.py test
post:
- coverage html -d $CIRCLE_ARTIFACTS
deployment:
production:
branch: master
commands:
- git remote add deploy dokku@<server ip>:<dokku app name>
- git push deploy maste
Travis-ci Automatic Deploy to Dokku¶
- Generate new ssh-key without password - Give a name to the file.
- Copy new ssh-key.pub to your project (you must be in your root project)
- Install Travis CI Command Line Client
- Login to travis
- Encrypt new ssh key (private) with travis and copy the command to decrypt in terminal
- Edit .travis.yml
- add ssh-key to dokku server (go to add-ssh section)
http://tannguyen.org/2017/02/set-up-hugo-dokku-and-travis/
Terminal:
$ ssh-keygen -t rsa
$ cp ~/.ssh/<ssh-key>.pub ./deploy_utils/deploy_key
$ sudo gem install travis
$ travis login
$ travis encrypt-file deploy_utils/deploy_key
->[.travis.yml] add before install:
before_install:
- openssl aes-256-cbc -K $encrypted_5d3fad67a2c7_key -iv $encrypted_5d3fad67a2c7_iv -in deploy_utils/deploy_key.enc -out deploy_utils/deploy_key -d
(this command should be given after run travis encrypt-file [...]
->[.travis.yml] add after script:
after_success:
- eval "$(ssh-agent -s)" #start the ssh agent
- chmod 600 deploy_utils/deploy_key # this key should have push access
- ssh-add deploy_utils/deploy_key
- echo -e "Host <hostname here>\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
- git remote add deploy <git-remote>
- git push deploy
Errors:¶
installing travis via sudo gem install travis
ERROR: Error installing travis: ERROR: Failed to build gem native extension.
Solution - https://github.com/travis-ci/travis.rb/issues/391
sudo apt-get install python-software-properties
sudo apt-add-repository ppa:brightbox/ruby-ng
sudo apt-get update
sudo apt-get install ruby2.1 ruby-switch
sudo ruby-switch --set ruby2.1
sudo apt-get install ruby2.1-dev
Add ssh-key to dokku¶
- Create a ssh-key
- send ssh-key to server
Terminal:
ssh-keygen -t rsa
cat <path to ssh-key> | ssh root@<your.ip.address> "sudo sshcommand acl-add dokku [description]"
Contributing¶
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions¶
Report Bugs¶
Report bugs at https://github.com/tyagow/django-base/issues.
If you are reporting a bug, please include:
- Your operating system name and version.
- Any details about your local setup that might be helpful in troubleshooting.
- Detailed steps to reproduce the bug.
Fix Bugs¶
Look through the GitHub issues for bugs. Anything tagged with “bug” is open to whoever wants to implement it.
Implement Features¶
Look through the GitHub issues for features. Anything tagged with “feature” is open to whoever wants to implement it.
Write Documentation¶
django-base could always use more documentation, whether as part of the official django-base docs, in docstrings, or even on the web in blog posts, articles, and such.
Submit Feedback¶
The best way to send feedback is to file an issue at https://github.com/tyagow/django-base/issues.
If you are proposing a feature:
- Explain in detail how it would work.
- Keep the scope as narrow as possible, to make it easier to implement.
- Remember that this is a volunteer-driven project, and that contributions are welcome :)
Get Started!¶
Ready to contribute? Here’s how to set up django-base for local development.
- Clone o repositório.
- Crie um virutalenv com o Python 3.5
- Ative o Virtualenv.
- Instale as dependencias.
- Configure a instancia com o .env
- Migre seus modelos para o Banco de Dados
- Roda o collectstatic para configurar arquivos staticos
- Execute os testes.
Digite no terminal:
git clone https://github.com/tyagow/django-base.git Nome-Do-Projeto
cd Nome-Do-Projeto
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp contrib/env-sample .env
python manage.py collectstatic
python manage.py migrate
python manage.py test
python manage.py runserver
Create a branch for local development:
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
- Submit a pull request through the GitHub website.
Pull Request Guidelines¶
Before you submit a pull request, check that it meets these guidelines:
- The pull request should include tests.
- If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.
- The pull request should work for Python 2.6, 2.7, and 3.5, and for PyPy. Check https://travis-ci.org/tyagow/django-base/pull_requests and make sure that the tests pass for all supported Python versions.
Credits¶
Development Lead¶
- django-base <tyagow@hotmail.com.br>
Contributors¶
None yet. Why not be the first?
Social Auth¶