Create A Django Project

ergun acun
2 min readFeb 24, 2023

--

This article consists of basic Django commands when starting a project.

Create a django project:

django-admin startproject <project-name>

Create an app within the project:

cd <project-name> && python manage.py startapp <app-name>

Your project structure should seem like below:

Run project at localhost:

python manage.py runserver

In order to add an html template, create a folder called templates at the root of your app. Then link the folder with your project with the following line to settings.py file.

TEMPLATES = [
{
.
.
'DIRS': [BASE_DIR/'templates'],
.
.
}

Create a file called url.py in your app inorder to manage urls. It should seem like below.

from django.urls import path
from . import views

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

To this point your project structure sould seem like below:

Create your index method at views.py file like below:

from django.shortcuts import render

def index(request):
return render(request, 'index.html')

Link your app to project with following line to settings.py file.

INSTALLED_APPS = [
.
.
.
'<app-name>' # 'post'
]

Add your app’s urls to project’s url.py like below:

"""blog URL Configuration

The `urlpatterns` list routes URLs to views.
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('<app-name>/urls')) #'post/urls'
]

Create your database models at models.py like below:

from django.db import models
from datetime import datetime

# Create your models here.

class Post(models.Model):
title = models.CharField(max_length=100)
body = models.CharField(max_length=1000000)
created_at = models.DateTimeField(default=datetime.now(), blank=True)

Migrate your model to database with commands below:

python manage.py makemigrations && python manage.py migrate

Create a super user for admin panel with command below:

python manage.py createsuperuser

Register your data model to admin panel from admin.py like below, then see the model at admin panel.

from django.contrib import admin
from .models import Post

# Register your models here.

admin.site.register(Post)

Retrieve database model objects at views.py like below:

from django.shortcuts import render
from .models import Post

# Create your views here.

def index(request):
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})

--

--

ergun acun
ergun acun

Written by ergun acun

Mobile Developer, Tech Enthusiast

No responses yet