How To Create a Django App and Connect it to a Database
How To Create a Django App and Connect it to a Database
In this tutorial, we will learn how to create a Django app and connect it to a database. Django is a popular Python web framework that allows developers to create robust web applications quickly and easily.
Step 1: Create a Django Project
The first step is to create a Django project. Open your terminal or command prompt and type the following command:
django-admin startproject myproject
This will create a new Django project with the name "myproject".
Step 2: Create a Django App
The next step is to create a Django app. Type the following command:
python manage.py startapp myapp
This will create a new Django app with the name "myapp".
Step 3: Connect to a Database
The next step is to connect your Django app to a database. In your project's settings.py file, add the following code:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
This code sets up a SQLite database for your Django app. You can replace it with your preferred database management system, such as PostgreSQL or MySQL.
Step 4: Create a Model
The next step is to create a model for your Django app. In your app's models.py file, add the following code:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
message = models.TextField()
def __str__(self):
return self.name
This code creates a model named "MyModel" with three fields: name, email, and message.
Step 5: Migrate the Database
The next step is to migrate your Django app's model to the database. Type the following command:
python manage.py makemigrations myapp
python manage.py migrate myapp
This will create a migration file and apply the changes to the database.
Step 6: Create Views and Templates
The next step is to create views and templates for your Django app. In your app's views.py file, add the following code:
from django.shortcuts import render
from .models import MyModel
def index(request):
mydata = MyModel.objects.all()
return render(request, 'index.html', {'mydata': mydata})
This code defines a view function named "index" that retrieves all data from the "MyModel" model and renders it using an HTML template.
Комментарии
Отправить комментарий