django getting started
Install Django:
bash pip install django
Create a Django project:
bash django-admin startproject myproject
Navigate to the project directory:
bash cd myproject
Create a Django app:
bash python manage.py startapp myapp
Define models in
models.py
of the created app (myapp
): ```python # myapp/models.py from django.db import models
class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.IntegerField() ```
Make migrations:
bash python manage.py makemigrations
Apply migrations:
bash python manage.py migrate
Create a Django admin superuser:
bash python manage.py createsuperuser
Start the development server:
bash python manage.py runserver
Access the admin site in a web browser (
http://127.0.0.1:8000/admin/
) and log in using the superuser credentials.Create instances of
MyModel
in the admin interface.Create views in
views.py
of the app (myapp
): ```python # myapp/views.py from django.shortcuts import render from .models import MyModeldef index(request): my_model_instances = MyModel.objects.all() return render(request, 'myapp/index.html', {'my_model_instances': my_model_instances}) ```
Create templates in the
templates
directory of the app (myapp
):myapp/templates/myapp/index.html
:html <h1>My Model Instances</h1> <ul> {% for instance in my_model_instances %} <li>{{ instance.field1 }} - {{ instance.field2 }}</li> {% endfor %} </ul>
Configure URLs in
urls.py
of the app (myapp
): ```python # myapp/urls.py from django.urls import path from . import viewsurlpatterns = [ path('', views.index, name='index'), ] ```
Include the app URLs in the project's
urls.py
: ```python # myproject/urls.py from django.contrib import admin from django.urls import include, pathurlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), ] ```
Run the development server again:
bash python manage.py runserver
Access the app in a web browser (
http://127.0.0.1:8000/myapp/
).