Python Django Project Setup and Database Integration
Classified in Computers
Written on in
English with a size of 4.14 KB
Python Django Project Setup
Follow these steps to initialize and configure your Python Django environment.
Initial Environment Navigation
- Step 1: Open the Command Prompt and use
cd..to navigate back. - Step 2: Use
cd..again to reach the desired root. - Step 3: Navigate to your Python directory:
cd Raj_Python. - Step 4: Enter your project folder:
cd mscit_dproject.
Creating the Project and Application
- Step 5: Create the project:
django-admin startproject [Project Name]. - Step 6: Navigate into the project folder:
cd [Project Name]. - Step 7: Create a new application:
python manage.py startapp [App Name]. - Step 8: Open the project in VS Code and configure settings.py.
Configuring settings.py
In settings.py, import the OS module and define your template directory:
import osTEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
Update the TEMPLATES and INSTALLED_APPS arrays:
TEMPLATES = [{'DIRS': [TEMPLATE_DIR], ...}]INSTALLED_APPS = ['App Name']
Routing and Views Configuration
- Step 9: Configure the main urls.py file:
from django.urls import path, includeurlpatterns = [path('index/', include('APPNAME.urls'))]
- Step 10: Define the initial view in views.py:
def Index(request): return render(request, "APPName.html")
- Step 11: Create a new file named urls.py inside your application folder:
from django.urls import pathfrom . import viewsurlpatterns = [path('appname/', views.appname, name='appname')]
Database Models and Migrations
- Step 12: Define your data structure in models.py:
class Student(models.Model): id = models.IntegerField(primary_key=True) fname = models.CharField(max_length=50) lname = models.CharField(max_length=50) age = models.IntegerField()
- Step 13: Execute migrations and start the server in the terminal:
python3 manage.py makemigrationspython3 manage.py migratepython3 manage.py runserver
Access the admin panel at 127.0.0.1/admin. Create a superuser with the following details:
- Command:
python3 manage.py createsuperuser - Username: root
- Email: [email protected]
- Password: admin@123
Admin Registration and Data Rendering
- Step 14: Register the model in admin.py:
from .models import Studentclass StudentAdmin(admin.ModelAdmin): list_display = ('id', 'fname', 'lname', 'age')admin.site.register(Student, StudentAdmin)
- Step 15: Update views.py to fetch database records:
from .models import Studentdef Index(request): s = Student.objects.all() context = {"list": s} return render(request, "firstapp/firstapp.html", context)
- Step 16: Create the firstapp.html template:
<h1>Hello World</h1>{% for i in list %} {{ i.id }} {{ i.fname }} {{ i.lname }} {{ i.age }}{% endfor %}
55