0% acharam este documento útil (0 voto)
34 visualizações22 páginas

Gaga Codex - WEB - 2022-04-03

O documento descreve conceitos e ferramentas de programação web como HTML, CSS, JavaScript, Django e banco de dados. O objetivo é registrar conhecimentos técnicos para desenvolvimento de frontend e backend.
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
34 visualizações22 páginas

Gaga Codex - WEB - 2022-04-03

O documento descreve conceitos e ferramentas de programação web como HTML, CSS, JavaScript, Django e banco de dados. O objetivo é registrar conhecimentos técnicos para desenvolvimento de frontend e backend.
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 22

Gaga’s Codex - Web

Gabriel Cardoso
7 de abril de 2022
Gabriel Cardoso Gaga’s Codex - Programação Web Django I

Resumo
O objetivo deste arquivo é registrar conhecimentos em programação WEB para desenvolvimento tanto de frontend com
backend.

Gabriel Cardoso Gaga’s Codex - Programação Web Django I


Sumário

R esumo I

1 Protocolos 1
1.1 IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 FTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 IMAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.5 POP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.6 SSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 Backend x Fronted x FullStack 1

3 Programação estática x Programação dinâmica 1

4 Conhecimentos básicos HTML 1

5 Conhecimentos básicos CSS 1

6 Conhecimentos básicos Javascript 1

7 Conhecimentos básicos Framework Frontend 1

8 Django Shell 2

9 Django Framework - Conceitos 2


9.1 Esqueleto do Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
9.1.1 Padrão MTV Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
9.1.2 Estrutura da aplicação . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
9.2 Fluxo de dados - Visão Global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
9.3 URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
9.4 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
9.5 Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
9.6 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
9.7 Sessão Admin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

10 Django Framework - Preparação para Desenvolvimento 5


10.1 Instalando o Django Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
10.2 Instalando Requirements a partir do requirements.txt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

11 Funcionamento e Configurações Básicas 5


11.1 Projeto Django x Aplicações Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
11.2 Arquivos de um projeto Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
11.2.1 db.sqlite3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
11.2.2 manage.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
11.2.3 requirements.txt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
11.2.4 urls.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
11.2.5 wsgi.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.3 Arquivos de uma Aplicação Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.3.1 Ditretório migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.3.2 Diretório statics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.3.3 Diretório templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
11.3.4 init .py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
11.3.5 settings.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
11.3.6 admin.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
11.3.6.1 Managing Users in the Admin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
11.3.7 apps.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
11.3.7.1 Projects and applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
11.3.8 models.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
11.3.9 tests.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
11.3.9.1 Running tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
11.3.10 urls.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
11.3.11 views.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
11.3.12 asgi.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

12 Funcionamento e Configurações Avançadas 14

13 Utilizando o banco MySQL 14

14 Arquivos estáticos no Django 14

15 Publicando na Internet 15

16 Auditando uma solução Django 16

17 Conteúdo Gaga’s CODEX 16


17.1 Documentação oficial Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
17.2 Fluxo de Criação - Django by Gaga . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
17.3 Elementos de um formulário /página . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Lista de Figuras
Lista de Tabelas
Gabriel Cardoso Gaga’s Codex - Programação Web Django 1

1 Protocolos
1.1 IP
1.2 HTTP
1.3 FTP
1.4 IMAP
1.5 POP
1.6 SSL
Arquivo: 03-protocolo-http-e-seus-verbos.pdf

2 Backend x Fronted x FullStack


Arquivo: 04-programacao-backend-x-frontend-x-full-stack.pdf

3 Programação estática x Programação dinâmica


Arquivo: 05-programacao-estatica-x-dinamica.pdf

4 Conhecimentos básicos HTML


Arquivo: 06-o-minimo-que-voce-precisa-saber-sobre-html.pdf
HTML = Estrutura da página

5 Conhecimentos básicos CSS


Arquivo: 07-o-minimo-que-voce-precisa-saber-sobre-css.pdf
CSS = Estilos

6 Conhecimentos básicos Javascript


Arquivo: 08-o-minimo-que-voce-precisa-saber-sobre-javascript.pdf
JavaScript = Comportamento/ações

7 Conhecimentos básicos Framework Frontend


Arquivo: 09-o-minimo-que-voce-precisa-saber-sobre-frameworks-frontend.pdf

Gabriel Cardoso Gaga’s Codex - Programação Web Django 1


Gabriel Cardoso Gaga’s Codex - Programação Web Django 2

8 Django Shell
Entra no Shell como um terminal python. Permite que se manipule banco de dados manualmente e execute funções python.
É possı́vel testar comandos python.
Para utilizar o comando Django Shell utilize: python manage.py shell.

9 Django Framework - Conceitos


9.1 Esqueleto do Site
9.1.1 Padrão MTV Django
MTV = Models Templates Views

USER -> BROWSER -> URL -> VIEW -> -> MODELS -> DATABASE -> TEMPLATES -> BROWSER -> USER

9.1.2 Estrutura da aplicação


Migrations Armazena as migrações de bancos de dados.

admin.py Serve para importar modelos para administar a aplicação

apps.py Nome da aplicação configurado por padrão

models.py É onde se cria os modelos de dados. Classes por exemplo.

tests.py Utiliza-se para criar testes para a aplicação.

views.py Contém as funções que serão chamadas pelas rotas para abrir os templates.

IMPORTANTE: Para cada aplicação criada, deve-se ir na seção settings.py do projeto, INSTALLED APPS e informar
o nome da aplicação. EX: ’core’,
IMPORTANTE 2: Ainda em settings.py na seção TEMPLATES em ’DIRS’ colocar ’templates’

9.2 Fluxo de dados - Visão Global


Depois de definirmos nossos modelos e criarmos alguns registros iniciais da biblioteca para trabalhar, é hora de escrever o
código que apresenta essas informações aos usuários. A primeira coisa que precisamos fazer é determinar quais informações
queremos exibir em nossas páginas e definir os URLs a serem usados para retornar esses recursos. Em seguida, criaremos
um mapeador de URLs, visualizações e modelos para exibir as páginas.
O diagrama a seguir descreve o fluxo de dados principal e os componentes necessários ao manipular solicitações e
respostas HTTP. Como já implementamos o modelo, os principais componentes que criaremos são:
Mapeadores de URL para encaminhar os URLs suportados (e qualquer informação codificada nos URLs) para as
funções de exibição apropriadas. View functions para obter os dados solicitados dos modelos, crie páginas HTML que
exibem os dados e retorne as páginas ao usuário para visualização no navegador. Templates para usar ao renderizar dados
nas visualizações.

9.3 URL
No pycharm, clique no diretório com o nome da aplicação, New, Python file. Dê o nome ”urls.py”.

Adicione o código no URLS da aplicação:


from django .urls import path
from . views import index , contato
urlpatterns = [
path(’’, index),
path(’contato ’, contato ),
]

Gabriel Cardoso Gaga’s Codex - Programação Web Django 2


Gabriel Cardoso Gaga’s Codex - Programação Web Django 3

Adicione o código no URLS do projeto:


from django . contrib import admin
from django .urls import path , include
urlpatterns = [
path(’admin/’, admin.site.urls),
path(’’, include (’core.urls ’)),
]

9.4 Views
Uma view é uma função.
Exemplo:

def index ( request ):


return render (request , ’index.html ’)

def contato ( request ):


return render (request , ’contato .html ’)
No exemplo acima foram criada views. A view executa um template que deve estar criado antes de se adicionar a
view.

9.5 Models
https://developer.mozilla.org/pt-BR/docs/Learn/Server-side/Django/Models
O projeto não tem Models. Quem possui models são as aplicações.
Os models são modelos de dados. São definidas classes nos models. Servirão para o Django criar bancos de dados
para o projeto.
O arquivo é chamado de ”models.py”.
Exemplo de criação de classes:
Confirme em settings se você informou a aplicação em INSTALLED APPS.
Em seguida é necessário realizar as migrações. Ele pegará todas as aplicações, todos os modelos e criar um arquivo
de migrations. Para isso, utilize o comando: python manage.py makemigrations
O banco de dado criado é referenciado no arquivo de settings na parte DATABASES.
O migration serve para gerenciar o histórico de modificações do banco de dados em comparação aos modelos de dados.
O próprio Django gerencia. Caso seja necessário voltar a um modelo de dados anterior será possı́vel.
Além de criar uma migration, é necessário aplicar a migração. Para isso utilize o comando: python manage.py migrate
Cada vez que for criada ou alterada uma classe deverá ser feito tanto a criação da migração quanto a migração.

9.6 Templates
É preciso configurar qual template será utilizado no arquivo settings.py do projeto.
É recomendado que o template de cada aplicação seja salvo independente dentro delas. Para isso deve-se criar uma
pasta dentro da aplicação chamada ”templates”.
Na seção TEMPLATES, na parte DIR, colocar o nome do(s) templates. EX:
% TEMPLATES = [
% {
% ’BACKEND ’: ’django . template . backends . django . DjangoTemplates ’,
% ’DIRS ’: [’templates ’],
% ’ APP DIRS ’: True ,
% ’OPTIONS ’: {
% ’ context processors ’: [
% ’django . template . context processors .debug ’,
% ’django . template . context processors . request ’,
% ’django . contrib .auth. context processors .auth ’,
% ’django . contrib . messages . context processors . messages ’,
% ],

Gabriel Cardoso Gaga’s Codex - Programação Web Django 3


Gabriel Cardoso Gaga’s Codex - Programação Web Django 4

% },
% },
%]
Deve ser configuradas também as views. Para isso é necessário clicar em New¿HTML File e criar as views de cada
página dentro da pasta ”templates”criada anteriormente.
O Django possui templates para url digitados incorretamente no dominio do site. Para Utilizar o template importe
com o comando no arquivo de views:
from django . shortcuts import get object or 404
A view do produto deverá também sofrer uma alteração conforme mostrado a seguir:
from django . shortcuts import get object or 404
from django .http import HttpResponse
from django . template import loader

def produto (request , pk):


#p r o d = P r o d u t o . o b j e c t s . g e t ( i d =pk )
prod = get object or 404 (Produto , id=pk)
context = {
’produto ’: prod
}
return render (request , ’produto .html ’, context )

def error404 (request , ex):


template = loader . get template (’404. html ’)
return HttpResponse ( content = template . render (), content type =’text/html; cha

def error500 ( request ):


template = loader . get template (’500. html ’)
return HttpResponse ( content = template . render (), content type =’text/html; cha
Para melhorar o modelo da pagina deve ser alterado o arquivo urls.
from django .conf.urls import handler404 , handler500
from core import views
handler404 = views. error404
handler500 = views. error500
O benefı́cio de mostrar uma página não encontrada por exemplo é que um usuário mal intencioado não saberia a
natureza do erro que ocorre, dessa forma aumenta-se a segurança do Site.

9.7 Sessão Admin


No arquivo de urls.py do projeto há uma rota padrão chamada ”admin”. Na settings também há uma admin. Essa rota
serve para acessar uma interface administrativa.
É necessário criar um usuário e senha para acessar essa interface. Para isso utilize o comando: python manage.py
createsuperuser
Efetue as configurações pelo próprio terminal.
Para acessar a área administrativa acesse o site conforme informado pelo servidor do Pycharm e adicione ”/admin”no
final. Efetue o login com o superusuario e senha criados. Pronto! A tela aberta é a área administrativa do site.
Para deixar a página em português, mude a linguagem no arquivo settings.py.
Nesta área é possı́vel alterar diversas configurações dos usuários cadastrados.
No diretório da aplicação há um arquivo admin.py.
Para importar os modelos utilize o código no arquivo admin.py:
from django . contrib import admin
from . models import Produto , Cliente
admin .site. register ( Produto )
admin .site. register ( Cliente )
É possı́vel melhorar a listagem utilizando o código:

Gabriel Cardoso Gaga’s Codex - Programação Web Django 4


Gabriel Cardoso Gaga’s Codex - Programação Web Django 5

from django . contrib import admin


from . models import Produto , Cliente
class ProdutoAdmin (admin. ModelAdmin ):
list display = (’nome ’,’preco ’,’estoque ’)

class ClienteAdmin (admin. ModelAdmin ):


list display = (’nome ’,’sobrenome ’,’email ’)
admin .site. register (Produto , ProdutoAdmin )
admin .site. register (Cliente , ClienteAdmin )
A função do arquivo admin é importar os modelos e registrar na página de administração.
É interessante mudar a rota padrão ”admin”para o acesso à área administrativa por segurança para evitar tentativa
de invasão.

10 Django Framework - Preparação para Desenvolvimento


10.1 Instalando o Django Framework
Versão necessário do Python: 3

Ferramenta utilizada para Python: PyCharm

Abra o Pycharm.

No Pycharm, crie um novo projeto.

No terminal do Pycharm digite: ”pip install django”


Busca versões de bibliotecas utilizadas atualmente

No terminal do Pycharm digite:


" pip freeze > requirements.txt "

10.2 Instalando Requirements a partir do requirements.txt

11 Funcionamento e Configurações Básicas


11.1 Projeto Django x Aplicações Django
Em um projeto Django é possı́vel ter várias aplicações. As aplicações criadas são plugáveis, ou seja, é possı́vel plugar
aplicações de um projeto em outro.

11.2 Arquivos de um projeto Django


11.2.1 db.sqlite3
11.2.2 manage.py
Executa comandos do projeto. Para executar o arquivo utilizar o comando: python manage.py runserver
Os comandos possı́veis para execução são:

[auth]
changepassword
createsuperuser

Gabriel Cardoso Gaga’s Codex - Programação Web Django 5


Gabriel Cardoso Gaga’s Codex - Programação Web Django 6

[contenttypes]
remove\_ stale\_ contenttypes
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
[sessions]
clearsessions
[staticfiles]
collectstatic
findstatic
runserver

Para mais informações execute o comando: python manage.py

Para mais informações sobre um comando especı́fico utilize o comando: python manage.py help [Comando]

11.2.3 requirements.txt
11.2.4 urls.py

Por padrão o arquivo URLS somente vem no projeto e não na aplicação. É possı́vel utilizar o URLs da aplicação importanto
para o projeto.
from django . contrib import admin
from django .urls import path
from core. views import index , contato
É importante também adicionar os paths para as paginas, mostrando a ”condição”de chamada. A página atribuı́da ao
parâmetro ” será a página inicial.
urlpatterns = [
path(’admin/’, admin.site.urls),
path(’’,index),
path(’contato ’, contato )
]
Caso uma rota não seja adicionada e um cliente solicita essa rota será mostrado um erro dizendo que não foi encontrada a
rota. Não é recomendado configurar as rotas no projeto e sim nas aplicações. O ideal seria:

Gabriel Cardoso Gaga’s Codex - Programação Web Django 6


Gabriel Cardoso Gaga’s Codex - Programação Web Django 7

from django . contrib import admin


from django .urls import path , include
urlpatterns = [
path(’admin/’, admin.site.urls),
path(’’, include (’core.urls ’)),
]

11.2.5 wsgi.py
Arquivo exclusivo para publicação. Geralmente não se mexe nesse arquivo.

11.3 Arquivos de uma Aplicação Django


No Terminal do Pycharm Pycharm certifique que o diretorio atual seja o mesmo do arquivo manage.py.
OBS: Para executar um comando no terminal do Django é necessário estar com o diretorio ativo no mesmo local do
arquivo manage.py.
Para verificar se existe o arquivo manage.py no diretório atual digite o código W indows: dir
Para criar a aplicação digite o código: django-admin startapp core
Onde core é o nome da aplicação

OBS: Caso dê problema tente reinstalar o django com o comando pip install django

11.3.1 Ditretório migrations


Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into
your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when
to run them, and the common problems you might run into.
The Commands
There are several commands which you will use to interact with migrations and Django’s handling of database schema:
ˆ migrate, which is responsible for applying and unapplying migrations.

ˆ makemigrations , which is responsible for creating new migrations based on the changes you have made to your
models.
ˆ sqlmigrate, which displays the SQL statements for a migration.

ˆ showmigrations, which lists a project’s migrations and their status.

You should think of migrations as a version control system for your database schema. makemigrations is responsible
for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for
applying those to your database.
The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed
to, and distributed as part of, its codebase. You should be making them once on your development machine and then running
the same migrations on your colleagues’ machines, your staging machines, and eventually your production machines.
Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see
in development and staging is, under the same circumstances, exactly what will happen in production. Django will make
migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can
reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations
later on (for example, if you’ve set custom validators) 1 2

11.3.2 Diretório statics


Django.contrib.staticfiles collects static files from each of your applications (and any other places you specify) into a single
location that can easily be served in production. For an introduction to the static files app and some usage examples, see
How to manage static files (e.g. images, JavaScript, CSS). For guidelines on deploying static files, see How to deploy static
files.
Settings: See staticfiles settings for details on the following settings:
1 It is possible to override the name of the package which contains the migrations on a per-app basis by modifying the MIGRATION MODULES

setting.
2 Referência: https:docs.djangoproject.comen4.0topicsmigrations

Gabriel Cardoso Gaga’s Codex - Programação Web Django 7


Gabriel Cardoso Gaga’s Codex - Programação Web Django 8

ˆ STATIC ROOT

ˆ STATIC URL

ˆ STATICFILES DIRS

ˆ STATICFILES STORAGE

ˆ STATICFILES FINDERS

11.3.3 Diretório templates


Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies
on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing
how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3.
A Django project can be configured with one or several template engines (or even zero if you don’t use templates).
Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for
the popular alternative Jinja2. Backends for other template languages may be available from third-parties. You can also
write your own custom backend, see Custom template backend
Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists
of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation.
Rendering means interpolating the template with context data and returning the resulting string.
The Django template language is Django’s own template system. Until Django 1.8 it was the only built-in option
available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a
pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and
you intend to distribute templates. Django’s contrib apps that include templates, like django.contrib.admin, use the DTL.
For historical reasons, both the generic support for template engines and the implementation of the Django template
language live in the django.template namespace.

11.3.4 init .py


Transofrma um diretório em um pacote no python

11.3.5 settings.py
Configurações Django do projeto

- DEBUG

Quando publicar o projeto o DEBUG deve ficar em FALSE. Impedirá das mensagens serem mostradas ao usuário.

- ALLOWED HOSTS

Serve para definir qual o domı́nio que deverá executar a aplicação. Somente será utilizada quando o DEBUG estiver em
FALSE. Parâmetro [ ’ ’ ] fará com que qualquer um tenha acesso.

- MIDDLEWARE

Verifica configurações de segurança como controle de usuário, sessão, comum, segurança de formulários, autenticação, etc...
É possı́vel criar os próprios middlewares.

- ROOT URLCONF

Configuração do URL raı́z.

- TEMPLATES

Tudo que será mostrado para o usuário.


Páginas em HTML

- WSGI APPLICATION

Gabriel Cardoso Gaga’s Codex - Programação Web Django 8


Gabriel Cardoso Gaga’s Codex - Programação Web Django 9

Padrão de criação de aplicações WEB Python que o Django segue.

- DATABASES

Por padrão o Django utiliza o Banco de dados SQLite3. Já é nativo no Python, não precisa instalar nada a mais.

- AUTH PASSWORD VALIDATORS

Configura recursos de validação de senhas de usuário por aproximação, senha comum, comprimento mı́nimo, somente números
e etc...

- LANGUAGE CODE

Linguagem padrão da aplicação. Por padrão Inglês EUA.

- TIMEZONE

Configuração do fuso horário.

- USE I18N

Configuração de multilinguagem.

- USE L10N

???

- USE TZ

Flag de ativação para utilizar Timezone.

- STATIC URL

Define o diretório Static dos arquivos CSS e Javascript.

11.3.6 admin.py
A web-based administrative back end is a standard feature of modern websites. The administrative interface, or admin
for short, allows trusted site administrators to create, edit and publish content, manage site users, and perform other
administrative tasks.
Django comes with a built-in admin interface. With Django’s admin you can authenticate users, display and handle
forms, and validate input; all automatically. Django also provides a convenient interface to manage model data.
When you ran startproject in Chapter 2, Django created and configured the default admin site for you. All you need to
do now is create an admin user (superuser) to log into the admin site. To create an admin user, run the following command
from inside your virtual environment:
python manage.py createsuperuser
Enter your desired username and press enter:
Username: admin
Django then prompts you for your email address:
Email address: [email protected]
The final step is to enter your password. Enter your password twice, the second time to confirm your password:
Password: ********** Password (again): ********* Superuser created successfully.
Now you have created an admin user, you’re ready to use the Django admin. Let’s start the development server and
explore.
First, make sure the development server is running, then open a web browser to http:127.0.0.1:8000admin. You should
see the admin’s login screen (Figure 7-1).
Log in with the superuser account you created. Once logged in, you should see the Django admin index page (Figure
7-2).
At the top of the index page is the Authentication and Authorization group with two types of editable content: Groups
and Users. They are provided by the authentication framework included in Django. We will look at users and groups later
in the chapter.

Gabriel Cardoso Gaga’s Codex - Programação Web Django 9


Gabriel Cardoso Gaga’s Codex - Programação Web Django 10

11.3.6.1 Managing Users in the Admin


If you remember from the beginning of the chapter, Django’s built-in authentication system is added to the admin interface
when you create a new project. With the admin you can:

ˆ Add and delete users

ˆ Edit existing users

ˆ Reset user passwords

ˆ Assign staff and/or superuser status to a user

ˆ Add or remove user permissions

ˆ Create user groups; and

ˆ Add users to a group

The superuser we created earlier has full access to all models in the admin and can add, change, and delete any model
record. In a real application, you will want to limit the number of users who have full access to your site.
Adding a new user is easy—go to the admin index page and click the green plus sign on the right of the Users entry
on the admin home page. Enter a username and password and click save to add the new user.
Return to the admin home page and click Users to open the user change list (Figure 7-12). Click on the username to
open the user edit screen.

11.3.7 apps.py
Django contains a registry of installed applications that stores configuration and provides introspection. It also maintains a
list of available models.
This registry is called apps and it’s available in django.apps:
from django .apps import apps
>>>
>>> apps. get app config (’admin ’). verbose name
’Administration ’

11.3.7.1 Projects and applications


The term project describes a Django web application. The project Python package is defined primarily by a settings module,
but it usually contains other things. For example, when you run django-admin startproject mysite you’ll get a mysite project
directory that contains a mysite Python package with settings.py, urls.py, asgi.py and wsgi.py. The project package is often
extended to include things like fixtures, CSS, and templates which aren’t tied to a particular application.
A project’s root directory (the one that contains manage.py) is usually the container for all of a project’s applications
which aren’t installed separately.
The term application describes a Python package that provides some set of features. Applications may be reused in
various projects.
Applications include some combination of models, views, templates, template tags, static files, URLs, middleware,
etc. They’re generally wired into projects with the INSTALLED APPS setting and optionally with other mechanisms such
as URLconfs, the MIDDLEWARE setting, or template inheritance.
It is important to understand that a Django application is a set of code that interacts with various parts of the
framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact
with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains
metadata in an AppConfig instance for each installed application.
There’s no restriction that a project package can’t also be considered an application and have models, etc. (which
would require adding it to INSTALLED APPS).
To configure an application, create an apps.py module inside the application, then define a subclass of AppConfig
there.
When INSTALLED APPS contains the dotted path to an application module, by default, if Django finds exactly one
AppConfig subclass in the apps.py submodule, it uses that configuration for the application. This behavior may be disabled
by setting AppConfig.default to False.
If the apps.py module contains more than one AppConfig subclass, Django will look for a single one where AppCon-
fig.default is True.
If no AppConfig subclass is found, the base AppConfig class will be used.
Alternatively, INSTALLED APPS may contain the dotted path to a configuration class to specify it explicitly:

Gabriel Cardoso Gaga’s Codex - Programação Web Django 10


Gabriel Cardoso Gaga’s Codex - Programação Web Django 11

INSTALLED APPS = [
...
’polls .apps. PollsAppConfig ’,
...
]

11.3.8 models.py
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the
data you’re storing. Generally, each model maps to a single database table.
The basics:
Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a
database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.
Quick example¶
This example model defines a Person, which has a first name and last name:
from django .db import models
class Person ( models .Model ):
first name = models . CharField ( max length =30)
last name = models . CharField ( max length =30)
first name and last name are fields of the model. Each field is specified as a class attribute, and each attribute maps
to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp person (
"id" serial NOT NULL PRIMARY KEY ,
" first name " varchar (30) NOT NULL ,
" last name " varchar (30) NOT NULL
);
Some technical notes:
The name of the table, myapp person, is automatically derived from some model metadata but can be overridden.
See Table names for more details. An id field is added automatically, but this behavior can be overridden. See Automatic
primary key fields. The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it’s worth noting
Django uses SQL tailored to the database backend specified in your settings file.
Using models
Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your
settings file and changing the INSTALLED APPS setting to add the name of the module that contains your models.py.
For example, if the models for your application live in the module myapp.models (the package structure that is created
for an application by the manage.py startapp script), INSTALLED APPS should read, in part:
INSTALLED APPS = [
#...
’myapp ’,
#...
]
When you add new apps to INSTALLED APPS, be sure to run manage.py migrate, optionally making migrations for
them first with manage.py makemigrations.
Fields
The most important part of a model – and the only required part of a model – is the list of database fields it defines.
Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean,
save, or delete.
Example:
from django .db import models
class Musician ( models .Model ):
first name = models . CharField ( max length =50)
last name = models . CharField ( max length =50)

Gabriel Cardoso Gaga’s Codex - Programação Web Django 11


Gabriel Cardoso Gaga’s Codex - Programação Web Django 12

instrument = models . CharField ( max length =100)


class Album ( models .Model ):
artist = models . ForeignKey (Musician , on delete = models . CASCADE )
name = models . CharField ( max length =100)
release date = models . DateField ()
num stars = models . IntegerField ()

11.3.9 tests.py
This document is split into two primary sections. First, we explain how to write tests with Django. Then, we explain how
to run them.
Writing tests¶
Django’s unit tests use a Python standard library module: unittest. This module defines tests using a class-based
approach.
Here is an example which subclasses from django.test.TestCase, which is a subclass of unittest.TestCase that runs
each test inside a transaction to provide isolation:
from django .test import TestCase
from myapp . models import Animal

class AnimalTestCase ( TestCase ):


def setUp (self ):
Animal . objects . create (name="lion", sound="roar")
Animal . objects . create (name="cat", sound="meow")

def test animals can speak (self ):


””” Animals that can speak are correctly i d e n t i f i e d ”””
lion = Animal . objects .get(name="lion")
cat = Animal . objects .get(name="cat")
self. assertEqual (lion.speak (), ’The lion says "roar"’)
self. assertEqual (cat.speak (), ’The cat says "meow"’)
When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of
unittest.TestCase) in any file whose name begins with test, automatically build a test suite out of those test cases, and run
that suite.
For more details about unittest, see the Python documentation.

11.3.9.1 Running tests


Once you’ve written tests, run them using the test command of your project’s manage.py utility:
./manage.py test
Test discovery is based on the unittest module’s built-in test discovery. By default, this will discover tests in any file
named “test*.py” under the current working directory.
You can specify particular tests to run by supplying any number of “test labels” to ./manage.py test. Each test label
can be a full Python dotted path to a package, module, TestCase subclass, or test method. For instance

11.3.10 urls.py
A request in Django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py
take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py
as per the queryset.
If we look at the 3-tier architecture of an app. Views are like the business logic layer. It is the controller in a typical
MVC (Model View Controller) design but Django has a slightly different naming convention called MVT (Model View
Template) where:
Model is the data access layer,
View is the business logic layer and
Template is the presentation layer.
Django has a urls.py file under the project by default. It also has a prep-defined path for the admin app. However,
Django recommends mapping all resources via another urls.py newly created under the app. The below explains it:
mysite – urls.py

Gabriel Cardoso Gaga’s Codex - Programação Web Django 12


Gabriel Cardoso Gaga’s Codex - Programação Web Django 13

from django . contrib import admin


from django .urls import path , include
urlpatterns = [
path(’admin/’, admin.site.urls),
path(’myapp/’, include (’myapp.urls ’)),
]
myapp – urls.py
from django .urls import path
from . import views

urlpatterns = [
path(’’, views.index), # app homepage
]
Django View Function
The URL mapping will redirect requests from project URLs to app URLs and then to the respective view function.
A sample view function code may look like this:
def index ( request ):
return render (request , ’index.html ’, { } )
or ,

from django .http import HttpResponse


def index ( request ):
return HttpResponse ("Hello World")
Here, the request is the URL request mapping and calling the view function. render combines a given template with
a given context dictionary. denotes the dictionary of values that can be added to the template context.

11.3.11 views.py
A view function, or view for short, is a Python function that takes a web request and returns a web response. This response
can be the HTML contents of a web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything,
really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere
you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of
putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application
directory.
A simple view
Here’s a view that returns the current date and time, as an HTML document:
from django .http import HttpResponse
import datetime

def current datetime ( request ):


now = datetime . datetime .now ()
html = "< html ><body >It is now %s. </body ></html >" % now
return HttpResponse (html)

11.3.12 asgi.py
Como fazer o deploy com ASGI
As well as WSGI, Django also supports deploying on ASGI, the emerging Python standard for asynchronous web
servers and applications.
Django’s startproject management command sets up a default ASGI configuration for you, which you can tweak as
needed for your project, and direct any ASGI-compliant application server to use.
Django includes getting-started documentation for the following ASGI servers:
How to use Django with Daphne How to use Django with Uvicorn

Gabriel Cardoso Gaga’s Codex - Programação Web Django 13


Gabriel Cardoso Gaga’s Codex - Programação Web Django 14

12 Funcionamento e Configurações Avançadas


Futuro...

13 Utilizando o banco MySQL


1. Crie um projeto Pycharm Vazio;
2. Devem ser instaladas todas as bibliotecas necessárias para rodar a aplicação. Execute o comando a seguir no terminal
do Pycharm:
pip install django whitenoise gunicorn django-bootstrap4 PyMySQL django-stdimage
3. Em seguida execute o comando:
pip freeze > requirements.txt
4. Verifique se o arquivo requirements.txt contém todas as bibliotecas necessárias conforme o passo anterior.

5. Utilize o comando a seguir para criar um projeto Django sem criação de subdiretórios.
django-admin startproject django2 .
6. Utilize o comando para criar uma aplicação
django-admin startapp core

7. No arquivo settings.py adicione as seguintes configurações:


ALLOWED HOSTS = [’*’]
INSTALLED APS = [
core,
bootstrap4,
stdimage,
]
MIDDLEWARE = [
whitenoise.middleware.WhiteNoiseMiddleware,
]
TEMPLATES = [
’DIRS’: [’templates’],
]
DATABASES = [
’ENGINE’: ’django.db.backends.mysql’,
’NAME’: ’django2’,
’USER’: ’geek’,
’PASSWORD’: ’university’,
’HOST’: ’localhost’,
’PORT’: ’3306’]
LANGUAGE CODE = ’pt−br’
TIME ZONE = ’America Sao Paulo’
STATIC ROOT = os.path.join(BASE DIR, ’staticfiles’)
8. Crie o banco de dados com o MySQL Workbench
CREATE DATABASE django2;

14 Arquivos estáticos no Django


Arquivos estáticos são do tipo:

ˆ CSS;

ˆ Javascript;

Gabriel Cardoso Gaga’s Codex - Programação Web Django 14


Gabriel Cardoso Gaga’s Codex - Programação Web Django 15

ˆ HTML.

Na raı́z da aplicação crie um novo diretório chamado de ”static”.


Dentro do diretório criado crie mais três diretórios chamados ”css”, ”js”, ”images”. (não imagens e sim images).
No arquivo settings.py do projeto, a configuração STATIC URL é utilizada como ’/ static/ ’ durante o desenvolvi-
mento. Na versão de publicação é utilizada a configuração:

STATIC URL = ’/ static /’


STATIC ROOT = os.path( BASE DIR , ’staticfiles ’)
O Django comuta os modos de acordo com a configuração DEBUG. Se True, será modo desenvolvimento, False será
com modo produção.
No modo produção o Django busca todos os arquivos static de todas as aplicações contidas no Projeto e centraliza no
diretório staticfiles dentro da pasta do projeto. Para coletar os arquivos estáticos é necessários rodar o comando:

python manage .py collectstatic


Por padrão o servidor Django criado no comando runserver quando em modo de produção, ou seja Debug = False,
não serve arquivos estáticos, para isso é necessário seguir os passos a seguir.
Devem ser instaladas as bibliotecas whitenoise e gunicorn com os comandos:

ˆ pip install whitenoise gunicorn

15 Publicando na Internet
Será utilizado o domı́nio do ”heroku”. Especificamente para esse caso as configurações do arquivo settings.py devem ter as
seguintes especificações:
ALLOWED HOSTS = [’ * ’]
MIDDLEWARE = [
’django . middleware . security . SecurityMiddleware ’,
’whitenoise . middleware . WhitheNoiseMiddleware ’,
’django . contrib . sessions . middleware . SessionMiddleware ’,
’django . middleware . common . CommonMiddleware ’,
’django . middleware .csrf. CsrfViewMiddleware ’,
’django . contrib .auth. middleware . AuthenticationMiddleware ’,
’django . contrib . messages . middleware . MessageMiddleware ’,
’django . middleware . clickjacking . XFrameOptionsMiddleware ’,
STATIC URL = ’/ static /’
STATIC ROOT = os.path.join( BASE DIR , ’staticfiles ’)
]
Devem ser instaladas as bibliotecas whitenoise e gunicorn com os comandos. O Whitenoise serve para o django mostrar
os arquivos estáticos em modo produção. O gunicorn é um servidor para rodar em modo produção.

1. pip install whitenoise gunicorn


2. No projeto, crie um arquivo na raı́z chamado .gitignore
3. Dentro do arquivo escreva:

pycache
*.*
*.pyc
.idea

4. Os arquivos sinalizados serão ignorados em commits no git.


5. Em seguida deve-se rodar o comando ”git init”, para iniciar o versionamento.
6. Digite o comando ”git add .”para carregar todos os arquivos.

Gabriel Cardoso Gaga’s Codex - Programação Web Django 15


Gabriel Cardoso Gaga’s Codex - Programação Web Django 16

7. Com o comando ”git status”é possı́vel ver se os arquivos foram carregados.


8. Caso seja a primeira vez que se utilize o git deverá configurar o usuário. Para configurar o usuário do git para realizar
commits execute:

git config –global user.email ”[email protected]


git config –global user.name ”Gaga”
Para comitar os arquivos escreva o comando: ”git commit -m ”Projeto Finalizado”

9. Acesse o site: www.heroku.com e Crie uma conta.

10. Acesse o site: https://devcenter.heroku.com/articles/getting-started-with-python. Faça o download do software no link


de acordo com o sistema operacional utilizado. Instale o client Heroku.
11. No Pycharm crie um novo arquivo dentro da raı́z do projeto chamado ”runtime.txt”. Dentro desse arquivo coloque a
versão do python utilizada. Ex: python-3.9.5. Salva e fecha.

12. Para atualizar o arquivo requirements com as novas bibliotecas execute o comando: pip freeze ¿ requirements.txt
13. Na pasta raı́z do projeto, crie um arquivo chamado ”Procfile”. Se o Pycharm perguntar o tipo informe que é um
arquivo de texto. Este arquivo será utilizado pelo Heroku. Dentro do arquivo criado escreva:

web: gunicorn Django1.wsgi –log-file -

14. execute novamente o comando:

git add . e git commit -m ”Adição de arquivos Heroku”

15. Agora é necessário logar no Heroku. Utilize o comando: ”heroku login”


16. Caso não loge tente reinstalar uma versão 32 bits por exemplo ou Reinicie o Pycharm.
17. Digite o comando para criar a aplicação:

heroku create django1-gaga –bu ildpack heroku/python

18. Para enviar o código e enviar parao projeto digite o comando ”git push heroku master”
19. Pronto! Acesse o site da sua aplicação.

16 Auditando uma solução Django


Verificações a serem feitas
CheckList:

17 Conteúdo Gaga’s CODEX


17.1 Documentação oficial Django
www.djangoproject.com

17.2 Fluxo de Criação - Django by Gaga


17.3 Elementos de um formulário /página

Gabriel Cardoso Gaga’s Codex - Programação Web Django 16

Você também pode gostar