As we said, talking about Django is talking about a web development framework using the Python programming language. Today we will teach you how you can develop an application connected to SQLite.
SQLite é uma base de dados relacional leve e muito rápida. É amplamente utilizada em apps que precisam de um armazenamento de dados incorporado, como apps móveis, pequenas apps para desktop, entre outras.
No seguimento dos nossos tutoriais em Django, hoje vamos ensinar com criar uma app, onde os dados são guardados em SQLite.
Vamos a um exemplo simples com SQLite
Para criar uma simples app com ligação à base de dados SQLite, usem os seguintes passos:
#1 – Criar um projeto
django-admin startproject mysite2
#2 – Create the app
python3 manage.py startapp app
#3 - Create the form
As mentioned earlier, Django allows you to create a database model and then import it into SQLite (or any other database management system). In this example, we will use the following form. In practice, we have a table by name memberwhich will have two fields: name and location.
#4 – Immigration
When executing the order com. makemigrationswe indicate to Django that there are changes to the model and that these changes should be taken into account.
python3 manage.py makemigrations app
After executing the command, you can see the result in/mysite2/app/migrations0001_initial.py.
#5 - Database migration
The matter Migrates INSTALLED_APPS, specified in the configuration file, parses and creates all necessary tables in the database as specified in mysite2/settings.py. If you do not need any of the components indicated in INSTALLED_APPS, you can comment.
python3 manage.py migrate
#6 – Entering data into the database e.g
To do this, we will access the SQLite shell using the python3 manager.py shell command. Next we will insert the data into the members table using the following command:
from app.models import Membro
membro1 = Membro(nome=“Pedro Pinto”, localidade=“Vila Real”)
membro2 = Membro(nome=“Carla”, localidade=“Viseu”)
membro3 = Membro(nome="Francisco", localidade="Lamego")
membro4 = Membro(nome="Inês", localidade="Faro")
membro5 = Membro(nome="Filipa", localidade="Porto")
membros_lista = [membro1, membro2, membro3, membro4, membro5]
for x in membros_lista:
x.save()
#6 – HTML template for displaying data
To display database data on an HTML page, we will create a template like the one shown in the following image. The given name was all_members.html
#7 - View creation
Finally, let's create a view with name Members
#8 – Implement the application
After everything is done, just launch the app to see if everything is ready to go. The result will be identical to the following:
And it was done. At first it may seem like a complicated process, but then it is simple. If you have any doubts or questions, leave them in the comments.
“Writer. Analyst. Avid travel maven. Devoted twitter guru. Unapologetic pop culture expert. General zombie enthusiast.”