|
| 1 | +PostgreSql + Django |
| 2 | +=================== |
| 3 | + |
| 4 | +:date: 2015-02-05 18:00 |
| 5 | +:tags: python, postresql, banco de dados |
| 6 | +:category: Python, Banco de dados |
| 7 | +:slug: postgresql-django |
| 8 | +:author: Regis da Silva |
| 9 | + |
| 10 | +:github: rg3915 |
| 11 | +:summary: Esta é a parte 3 (de 3) da série de posts sobre PostgreSql... |
| 12 | + |
| 13 | +Se você já leu o *Tutorial Postgresql* e *Postgresql + Python3*, este post é uma continuação. Aqui nós veremos usar PostgreSql no `Django <http://pythonclub.com.br/tutorial-django-17.html>`_. |
| 14 | + |
| 15 | +Para quem já leu `Two Scoops of Django <http://twoscoopspress.com/products/two-scoops-of-django-1-6>`_ sabe que o `PyDanny <http://www.pydanny.com/>`_ recomenda fortemente o uso do `PostgreSQL <http://www.postgresql.org/>`_ em seus projetos. |
| 16 | + |
| 17 | +Então vejamos aqui como configurar o Postgresql para ser usado no `Django <http://pythonclub.com.br/tutorial-django-17.html>`_. |
| 18 | + |
| 19 | +Precisamos criar o banco manualmente |
| 20 | +------------------------------------ |
| 21 | + |
| 22 | +Começando... |
| 23 | + |
| 24 | +.. code-block:: bash |
| 25 | +
|
| 26 | + $ sudo su - postgres |
| 27 | +
|
| 28 | +Veja o prompt: |
| 29 | + |
| 30 | +.. code-block:: bash |
| 31 | +
|
| 32 | + postgres@myuser:~$ |
| 33 | +
|
| 34 | +Criando o banco |
| 35 | + |
| 36 | +.. code-block:: bash |
| 37 | +
|
| 38 | + $ createdb mydb |
| 39 | +
|
| 40 | +Se existir o banco faça |
| 41 | + |
| 42 | +.. code-block:: bash |
| 43 | +
|
| 44 | + $ dropdb mydb |
| 45 | +
|
| 46 | +e crie novamente. Para sair digite |
| 47 | + |
| 48 | +.. code-block:: bash |
| 49 | +
|
| 50 | + $ exit |
| 51 | +
|
| 52 | +Django |
| 53 | +------ |
| 54 | + |
| 55 | +Vamos criar um virtualenv e instalar o `psycopg2 <http://initd.org/psycopg/docs/install.html#use-a-python-package-manager>`_, além do django. |
| 56 | + |
| 57 | +.. code-block:: bash |
| 58 | +
|
| 59 | + virtualenv -p /usr/bin/python3 teste |
| 60 | + cd teste |
| 61 | + source bin/activate |
| 62 | + pip install psycopg2 django |
| 63 | + pip freeze |
| 64 | + pip freeze > requirements.txt |
| 65 | +
|
| 66 | +**Dica**: Para diminuir o caminho do prompt digite |
| 67 | + |
| 68 | +.. code-block:: bash |
| 69 | +
|
| 70 | + $ PS1="(`basename \"$VIRTUAL_ENV\"`):/\W$ " |
| 71 | +
|
| 72 | +**Dica**: |
| 73 | + |
| 74 | +.. code-block:: bash |
| 75 | + |
| 76 | + vim ~/.bashrc + |
| 77 | + alias manage='python $VIRTUAL_ENV/manage.py' |
| 78 | +
|
| 79 | +Com isto nós podemos usar apenas ``manage`` ao invés de ``python manage.py``. |
| 80 | + |
| 81 | +Criando o projeto |
| 82 | +^^^^^^^^^^^^^^^^^ |
| 83 | + |
| 84 | +.. code-block:: bash |
| 85 | +
|
| 86 | + django-admin.py startproject myproject . |
| 87 | + cd myproject |
| 88 | + python ../manage.py startapp core |
| 89 | +
|
| 90 | +**Edite o settings.py** |
| 91 | + |
| 92 | +.. code-block:: python |
| 93 | +
|
| 94 | + DATABASES = { |
| 95 | + 'default': { |
| 96 | + 'ENGINE': 'django.db.backends.postgresql_psycopg2', |
| 97 | + 'NAME': os.path.join(BASE_DIR, 'mydb'), |
| 98 | + 'USER': 'myuser', |
| 99 | + 'PASSWORD': 'mypassword', |
| 100 | + 'HOST': '127.0.0.1', |
| 101 | + 'PORT': '', # 8000 is default |
| 102 | + } |
| 103 | + } |
| 104 | +
|
| 105 | +**Rode a aplicação** |
| 106 | + |
| 107 | +.. code-block:: bash |
| 108 | +
|
| 109 | + python manage.py migrate |
| 110 | + python manage.py runserver |
| 111 | +
|
| 112 | +http://127.0.0.1:8000/ ou http://localhost:8000/ |
| 113 | + |
| 114 | +**Edite o models.py** |
| 115 | + |
| 116 | +.. code-block:: python |
| 117 | +
|
| 118 | + from django.db import models |
| 119 | + from django.utils.translation import ugettext_lazy as _ |
| 120 | + |
| 121 | + |
| 122 | + class Person(models.Model): |
| 123 | + name = models.CharField(_('Nome'), max_length=50) |
| 124 | + email = models.EmailField(_('e-mail'), max_length=30, unique=True) |
| 125 | + age = models.IntegerField(_('Idade')) |
| 126 | + active = models.BooleanField(_('Ativo'), default=True) |
| 127 | + created_at = models.DateTimeField( |
| 128 | + _('Criado em'), auto_now_add=True, auto_now=False) |
| 129 | + |
| 130 | + class Meta: |
| 131 | + ordering = ['name'] |
| 132 | + verbose_name = "pessoa" |
| 133 | + verbose_name_plural = "pessoas" |
| 134 | + |
| 135 | + def __str__(self): |
| 136 | + return self.name |
| 137 | +
|
| 138 | +Leia mais em |
| 139 | + |
| 140 | +`Tutorial Django 1.7 <http://pythonclub.com.br/tutorial-django-17.html>`_ |
| 141 | + |
| 142 | +`Como criar um site com formulário e lista em 30 minutos? <http://pythonclub.com.br/criar-site-com-form-lista-30-min.html>`_ |
| 143 | + |
| 144 | +**Edite o settings.py** novamente |
| 145 | + |
| 146 | +Em *INSTALLED_APPS* insira a app *core*. |
| 147 | + |
| 148 | +.. code-block:: python |
| 149 | +
|
| 150 | + INSTALLED_APPS = ( |
| 151 | + ... |
| 152 | + 'myproject.core', |
| 153 | + ) |
| 154 | +
|
| 155 | +**Faça um migrate** |
| 156 | + |
| 157 | +.. code-block:: bash |
| 158 | +
|
| 159 | + python manage.py makemigrations core |
| 160 | + python manage.py migrate |
| 161 | +
|
| 162 | +Um pouco de shell |
| 163 | +^^^^^^^^^^^^^^^^^ |
| 164 | + |
| 165 | +.. code-block:: bash |
| 166 | +
|
| 167 | + python manage.py shell |
| 168 | + Python 3.4.0 (default, Apr 11 2014, 13:05:18) |
| 169 | + [GCC 4.8.2] on linux |
| 170 | + Type "help", "copyright", "credits" or "license" for more information. |
| 171 | + (InteractiveConsole) |
| 172 | + >>> |
| 173 | +
|
| 174 | +
|
| 175 | +
|
| 176 | +Serve para manipular a app pelo **terminal**. |
| 177 | + |
| 178 | +.. code-block:: python |
| 179 | +
|
| 180 | + >>> from myproject.core.models import Person |
| 181 | + >>> p = Person.objects.create(name='Regis',email='[email protected]',age=35) |
| 182 | + >>> p.id |
| 183 | + >>> p.name |
| 184 | + >>> p.email |
| 185 | + >>> p.age |
| 186 | + >>> p.active |
| 187 | + >>> p.created_at |
| 188 | + >>> p = Person.objects.create(name='Xavier',email='[email protected]',age=66,active=False) |
| 189 | + >>> persons = Person.objects.all().values() |
| 190 | + >>> for person in persons: print(person) |
| 191 | + >>> exit() |
| 192 | +
|
| 193 | +Leia mais em |
| 194 | + |
| 195 | +*Tutorial PostgreSql* |
| 196 | + |
| 197 | +*PostgreSql + Python3* |
| 198 | + |
| 199 | +`Tutorial Django 1.7 <http://pythonclub.com.br/tutorial-django-17.html>`_ |
| 200 | + |
| 201 | +`Como criar um site com formulário e lista em 30 minutos? <http://pythonclub.com.br/criar-site-com-form-lista-30-min.html>`_ |
| 202 | + |
| 203 | +`How To Install and Configure Django with Postgres, Nginx, and Gunicorn <https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn>`_ |
| 204 | + |
| 205 | +http://www.postgresql.org/docs/9.4/static/tutorial-createdb.html |
| 206 | + |
| 207 | +http://www.postgresql.org/docs/9.4/static/index.html |
| 208 | + |
| 209 | +http://www.postgresql.org/docs/9.4/static/tutorial-sql.html |
0 commit comments