---
# System prepended metadata

title: Apostila Python 3.8.2 Django
tags: [apostila, python]

---

# Apostila Python 3.8.2 Django

* visual code
* instalar plugins 
	* phyton para vc code
	* kite phyton
	* linting, debbugi phyton
* baixar e instalar o phyton
* instalar sem colocar email
* marcar automaticamente


```
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
python -m pip install Django
```

**NO LINUX:**
```
sudo apt-get install python3.7
sudo apt-get install python3-pip

python3 -V
pip3 -V

pip3 install Django
django-admin --version
```

**ATUALIZANDO A VERSAO DO PIP3**
```
pip3 install --upgrade pip
```

https://tecadmin.net/install-django-on-ubuntu/

Step 3 – Create A Django Application
cd /var/www
django-admin startproject testedom

cd django_app
python3 manage.py migrate

Step 4 – Create Super User
python3 manage.py createsuperuser

Step 5 – Run Django Application
vi django_app/settings.py
ALLOWED_HOSTS = ['192.168.1.239']
python3 manage.py runserver 0.0.0.0:8000
http://192.168.1.239:8000


sh pycharm.sh

## NO PYCHARM:
CRIANDO PROJETO
https://www.treinaweb.com.br/blog/criando-o-primeiro-projeto-django/

COMANDO PARA RODAR O DJANGO
python manage.py runserver

RODA NESSA PORTA
http://127.0.0.1:8000/

---
https://tutorial.djangogirls.org/pt/django_models/
python manage.py startapp blog
criar classe modelo
python manage.py makemigrations blog - criando banco
python manage.py migrate blog - criar as tabelas
alterar admin.py
python manage.py runserver



## NO DIRETORIO DO PYCHARM 26-04-2020

CRIAR PROJETO DJANGO

Rodar no terminal:
django-admin startproject testedom

abrir o Pycharm nesse diretorio

COMANDO PARA RODAR O DJANGO
python manage.py runserver

****************
## NO WINDOWS

https://medium.com/horadecodar/instalando-django-2-1-e-criando-um-projeto-windows-e-linux-67cbff58496c

### CRIAR A ENV
python -m venv myvenv
myvenv\Scripts\activate

python -m pip install --upgrade pip
criar requirements.txt
escrever nele Django~=3.0.5
pip install -r requirements.txt
myvenv\Scripts\activate



django-admin.exe startproject mysite .
python manage.py migrate

python manage.py startapp blog
classe models
python manage.py makemigrations blog
 manage.py migrate blog
 
https://docs.djangoproject.com/en/3.0/intro/tutorial01/ 
django-admin startproject mysite
python manage.py startapp polls


---

### OUTRA FORMA NO WINDOWS:
https://docs.python.org/pt-br/3/tutorial/venv.html

Criar um diretorio, entrar nele e dar os comandos pelo PowerShell **administrador**
```
python3 -m venv tutorial-env
tutorial-env\Scripts\activate.bat
```
![](https://i.imgur.com/EfAkRpU.png)

---
Digitar no terminal:
```
python
```
![](https://i.imgur.com/M8Q9jom.png)

---

Dando o mesmo comando pelo terminal do **Visual Code**
![](https://i.imgur.com/3BAIOTY.png)

---

Abrir um outro terminal e instalar as bibliotecas:
:point_right: **(Digitar tudo numa linha só)**
```
pip install django djangorestframework markdown 
django-filter django-cors-headers
```
![](https://i.imgur.com/CkkImJz.png)

---

Para listar as biblotecas instaladas:
```
pip freeze 
```
![](https://i.imgur.com/yYXt1tY.png)

---

Estrutura do diretorio:
![](https://i.imgur.com/LntzDr1.png)
![](https://i.imgur.com/ExbjNwy.png)
![](https://i.imgur.com/kKl0pLU.png)

---

Com o Django instalado vamos **iniciar** o projeto.
```
django-admin startproject projeto_belem
```
![](https://i.imgur.com/BqmVvhs.png)

---

Entrar no diretorio 
```
cd projeto_belem
```
![](https://i.imgur.com/DSQHLM0.png)

---

Criar o projeto **alunos**
```
django-admin startapp alunos
```
![](https://i.imgur.com/JvaIvDL.png)

Comando **Migrate** para o django criar as nossas tabelas do DB
```
python manage.py migrate
```
![](https://i.imgur.com/5vpXcZ8.png)

---

Criar um usuário para acessar o Django
```
python manage.py createsuperuser
```
**Exemplo:** 
Usuario: Belem
Senha: 1234
![](https://i.imgur.com/4hDlTQ3.png)

---

Iniciar o servidor
```
python manage.py runserver
```
![](https://i.imgur.com/zgWxZGH.png)

---

Visualizando no browser
![](https://i.imgur.com/JRSCnuw.png)

---

Logando como **administrador:**
http://127.0.0.1:8000/admin
![](https://i.imgur.com/G5K0Nom.png)

---

Logando com usuario: **Belem** e senha: **1234**
![](https://i.imgur.com/MVnQe6U.png)

---

Logado
![](https://i.imgur.com/SBJpHtJ.png)

---

Em **projeto_belem/projeto_belem/settings.py** vamos configurar os INSTALLED_APPS.
```python=
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'alunos',
    'rest_framework'
]
```
![](https://i.imgur.com/3Bc5PCs.png)

---

### Em **alunos/models.py**
```python=
from django.db import models

class Aluno(models.Model):
    nome = models.CharField(max_length=200)
    curso = models.CharField(max_length=200)
    data_nasc = models.PositiveSmallIntegerField()
    matricula = models.BooleanField(default=True)
```

Realizamos as migrations
```
python manage.py makemigrations
```
![](https://i.imgur.com/lf09Aqd.png)

---

![](https://i.imgur.com/Y8h3P4D.png)

---

### 0001_initial.py
Gerado automaticamente
```python=
# Generated by Django 3.0.5 on 2020-05-04 14:29

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Aluno',
            fields=[
                ('id', models.AutoField(auto_created=True, 
                primary_key=True, serialize=False, verbose_name='ID')),
                ('nome', models.CharField(max_length=200)),
                ('curso', models.CharField(max_length=200)),
                ('data_nasc', models.PositiveSmallIntegerField()),
                ('matricula', models.BooleanField(default=True)),
            ],
        ),
    ]

```

Migrar o model
```
python manage.py migrate 
```
![](https://i.imgur.com/LFtv4XU.png)

---

### projeto_belem/alunos/admin.py
```python=
from django.contrib import admin
from .models import Aluno

admin.site.register(Aluno)
```

Iniciar o servidor
```
python manage.py runserver
```
Visualizando no browser. Mostra **alunos**
http://127.0.0.1:8000/admin/
![](https://i.imgur.com/2ywFyL2.png)

---

### models.py
Adicionando toString na classe
```python=
from django.db import models


class Aluno(models.Model):
    nome = models.CharField(max_length=200)
    curso = models.CharField(max_length=200)
    data_nasc = models.PositiveSmallIntegerField()
    matricula = models.BooleanField(default=True)

    def __str__ (self):
        return self.nome
        return self.curso
        return self.data_nasc
        return self.matricula
```

Confirmar alterações na classe
```
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
```
![](https://i.imgur.com/FPRjWSG.png)

---

### projeto_belem/projeto_belem/urls.py
```python=
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls'))
]
```
![](https://i.imgur.com/foa20rK.png)

### projeto_belem/projeto_belem/settings.py
Adicionar ao final da classe
```python=80
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}
```
![](https://i.imgur.com/vCIeiMK.png)

---

Criar o diretorio **`api`** e os arquivos:
* `serializers.py`
* `views.py`
* `urls.py`
* `__init__.py` 
![](https://i.imgur.com/P4YZkJE.png)

---

### projeto_belem/alunos/api/serializers.py
```python=
from rest_framework import serializers
from alunos.models import Aluno

class AlunoSerlialiser(serializers.ModelSerializer):

    class Meta:
        model = Aluno
        fields = ('__all__')
```

### projeto_belem/alunos/api/views.py
```python=
from  rest_framework import viewsets
from alunos.models import Aluno
from alunos.api.serializers import AlunoSerlialiser

class AlunoViewSet(viewsets.ModelViewSet):
    queryset = Aluno.objects.all().filter(matricula=True)
    serializer_class = AlunoSerlialiser
```

### projeto_belem/alunos/api/urls.py
```python=
from django.urls import path, include
from rest_framework import routers
from .views import AlunoViewSet

router = routers.DefaultRouter()
router.register('alunos', AlunoViewSet)

urlpatterns = [
    path('', include((router.urls)))
]
```

### projeto_belem/alunos/api/`__init__.py`
```python=



```

### projeto_belem/projeto_belem/urls.py
```python=
"""projeto_belem URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('api/', include('alunos.api.urls'))
]

```

## Projeto finalizado
http://127.0.0.1:8000/
![](https://i.imgur.com/yezQIwc.png)

---

http://127.0.0.1:8000/admin/
![](https://i.imgur.com/saRzmSv.png)

---

http://127.0.0.1:8000/api/
![](https://i.imgur.com/hMXX69M.png)

---

http://127.0.0.1:8000/api/alunos/
![](https://i.imgur.com/bjCkbjN.png)

## :fire: Criando projeto many to many

Criar um diretorio para armazenar os projetos
```
mkdir projetosMany
```

Criar a env e ativar
```
python3 -m venv proj_many_env
proj_many_env\Scripts\activate.bat
```

Fazer as instalações das bibliotecas:
```python=
pip install django
pip install psycopg2
pip install django djangorestframework markdown django-filter
pip install requests
pip install django-cors-headers
pip install httpie
```
.
```
pip install django
```
![](https://i.imgur.com/jdx1lcV.png)

```
pip install psycopg2
```
![](https://i.imgur.com/zkcLIpv.png)

```
pip install django djangorestframework markdown django-filter
```
![](https://i.imgur.com/Mi3bS1k.png)

```
pip install requests
```
![](https://i.imgur.com/HFUTe23.png)

```
pip install django-cors-headers
```
![](https://i.imgur.com/FctWLws.png)

```
pip install httpie
```
![](https://i.imgur.com/CJosKfv.png)

Criar o projeto django chamado **sistema**
```
django-admin startproject sistema
```
![](https://i.imgur.com/ncwskOt.png)

Entrar no diretorio criado:
```
cd sistema 
```
![](https://i.imgur.com/MNj4PNH.png)

Criar o app.
```
python manage.py startapp restEstoque
```
![](https://i.imgur.com/ZMzbZ55.png)

Projeto criado
![](https://i.imgur.com/nIOuryC.png)


Alterar **`models.py`**
```python=
from django.db import models

class Peca(models.Model):
    idPeca = models.AutoField(primary_key= True,)
    valor = models.FloatField()
    descricao = models.CharField(max_length=255)

    def __str__(self):
        return '%d, %f, %s' % (self.idPeca, self.valor, self.descricao)
    def __repr__(self):
        return '%d, %f, %s' % (self.idPeca, self.valor, self.descricao)
    pass

class Usuario(models.Model):
    idUsuario  = models.AutoField(primary_key=True, )
    nome = models.CharField(max_length= 100)

    def __repr__(self):
        return '%d, %s' % (self.idUsuario, self.nome)
    def __str__(self):
        return '%d, %s' % (self.idUsuario, self.nome)
    pass

class Demanda(models.Model):
    idDemanda = models.AutoField(primary_key = True, )
    rua = models.CharField(max_length=100)
    bairro = models.CharField(max_length=100)
    numero = models.CharField(max_length=100)
    cep = models.CharField(max_length=100)
    cidade = models.CharField(max_length=100)
    status = models.IntegerField()
    usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE)
    pecas  = models.ManyToManyField(Peca)

    def __str__(self):
        return '%d, %s, %s, %s, %s, %s, %s' % (self.idDemanda, self.rua, self.bairro, self.numero, self.cep, self.cidade, self.status)
    def __repr__(self):
        return '%d, %s, %s, %s, %s, %s, %s' % (self.idDemanda, self.rua, self.bairro, self.numero, self.cep, self.cidade, self.status)
    pass
```

Alterar **`settings.py`**, inserindo os apps e o banco de dados
```
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'restEstoque'
]

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'aulateste',
        'USER': 'postgres',
        'HOST': 'localhost',
        'PASSWORD': 'coti',
        'PORT': '5432',
    }
}
```

Alterar **`Urls.py`** do projeto (sistema). Deixar comentado para rodar o **makemigrations**
```python=
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from rest_framework.authtoken.views import obtain_auth_token

# from restEstoque.urls import router

urlpatterns = [
    path('api/token/', obtain_auth_token, name='api-token'),
    # url(r'^api/', include(router.urls))

]
```

Fazer a **migration**
```
python manage.py makemigrations restEstoque
```
![](https://i.imgur.com/5Exlfyw.png)

```
python manage.py migrate
```
![](https://i.imgur.com/D0vkjRe.png)

Classe gerada **`0001_initial.py`**
```python=
# Generated by Django 3.0.5 on 2020-05-13 19:15

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Peca',
            fields=[
                ('idPeca', models.AutoField(primary_key=True, serialize=False)),
                ('valor', models.FloatField()),
                ('descricao', models.CharField(max_length=255)),
            ],
        ),
        migrations.CreateModel(
            name='Usuario',
            fields=[
                ('idUsuario', models.AutoField(primary_key=True, serialize=False)),
                ('nome', models.CharField(max_length=100)),
            ],
        ),
        migrations.CreateModel(
            name='Demanda',
            fields=[
                ('idDemanda', models.AutoField(primary_key=True, serialize=False)),
                ('rua', models.CharField(max_length=100)),
                ('bairro', models.CharField(max_length=100)),
                ('numero', models.CharField(max_length=100)),
                ('cep', models.CharField(max_length=100)),
                ('cidade', models.CharField(max_length=100)),
                ('status', models.IntegerField()),
                ('pecas', models.ManyToManyField(to='restEstoque.Peca')),
                ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restEstoque.Usuario')),
            ],
        ),
    ]

```
Criar o admin do projeto. Usuario: belem, senha: 123
```
python manage.py createsuperuser
```
![](https://i.imgur.com/oqlM8c3.png)



Dentro de **sistema** criar o diretorio **api**
![](https://i.imgur.com/5zGSlpg.png)

---

Dentro de **restEstoque** criar o arquivo **`serializers.py`**
```python=
from rest_framework import serializers
from .models import *

class PecaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Peca
        fields = ('idPeca', 'valor', 'descricao')
    pass

class UsuarioSerializer(serializers.ModelSerializer):
    class Meta:
        model = Usuario
        fields = ('idUsuario', 'nome')
    pass

class DemandaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Demanda
        fields = ('idDemanda', 'rua', 'bairro', 'numero', 'cidade', 'cep', 'status', 'usuario', 'pecas')
    pass
```



Alterar a **`views.py`** do **rest_projeto**
```python=
from django.shortcuts import render

from .models import *
from .serializers import *
from rest_framework import viewsets, authentication, permissions, serializers,reverse

class DemandaViewSet(viewsets.ModelViewSet):
    queryset = Demanda.objects.order_by('idDemanda')
    serializer_class = DemandaSerializer
    links = serializers.SerializerMethodField()
    # PUT, DELETE, POST, GET
    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('demanda-detail', kwargs={'pk': obj.pk}, request=request)
        }
        pass
    pass

class PecaViewSet(viewsets.ModelViewSet):
    queryset = Peca.objects.order_by('valor')
    serializer_class = PecaSerializer
    links = serializers.SerializerMethodField()
    # PUT, DELETE, POST, GET
    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('peca-detail', kwargs={'pk': obj.pk}, request=request)
        }
        pass
    pass

class UsuarioViewSet(viewsets.ModelViewSet):
    queryset = Usuario.objects.order_by('nome')
    serializer_class = UsuarioSerializer
    links = serializers.SerializerMethodField()
    # PUT, DELETE, POST, GET
    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('usuario-detail', kwargs={'pk': obj.pk}, request=request)
        }
        pass
    pass

class DefaultsMixin(object):
    authentication_classes = (
        authentication.BasicAuthentication,
        authentication.TokenAuthentication
    )
    permission_classes = (
        permissions.IsAuthenticated,
    )
    pass
```

Alterar **`urls.py`** dentro do **restEstoque**
```python=
from rest_framework.routers import SimpleRouter, DefaultRouter
from .import views

router = DefaultRouter()
router.register(r'demandas', views.DemandaViewSet)
router.register(r'pecas', views.PecaViewSet)
router.register(r'usuarios', views.UsuarioViewSet)
```

Alterar **`urls.py`** de **sistema**. Descomentar
```python=
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from rest_framework.authtoken.views import obtain_auth_token

from restEstoque.urls import router

urlpatterns = [
    path('api/token/', obtain_auth_token, name='api-token'),
    url(r'^api/', include(router.urls))
]
```

Para rodar:
```python=
python manage.py runserver 
```

:eye: Visualizando no banco
![](https://i.imgur.com/a9vK0yN.png)

###### tags: `python` `apostila`