Create a Django Project Crash to Build

Install Django

pip install django

Create a new Django project.

django-admin startproject myproject
cd myproject

Create a new app

python manage.py startapp myapp

Modify the models.py file in your myapp folder.

# myapp/models.py
from django.db import models

class MyModel(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Apply migrations and create the database.

python manage.py makemigrations
python manage.py migrate

Create a simple view in myapp/views.py.

# myapp/views.py
from django.shortcuts import render
from .models import MyModel

def index(request):
    my_objects = MyModel.objects.all()
    return render(request, 'myapp/index.html', {'my_objects': my_objects})

Create a template in myapp/templates/myapp/index.html.

<!-- myapp/templates/myapp/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>My Django App</title>
</head>
<body>
    <h1>Welcome to My Django App</h1>
    <ul>
        {% for obj in my_objects %}
            <li>{{ obj.title }} - {{ obj.content }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Configure the URLs

Configure the URLs in myapp/urls.py.

# myapp/urls.py
from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='index'),
]

Include the app's URLs in the project's urls.py.

# myproject/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Run the development server:

python manage.py runserver

Now, you can visit http://localhost:8000 in your browser and see the simple Django app in action.


Similar Articles