Build your first app with Django

Build your first app with Django Nov. 2, 2020

Step 1: Install Python. Download python from here

[Explanation: Django is a python framework to create websites. So python is required]

Step 2: Install Django by running the pip install django command in terminal.

[Explanation: pip is a python package manager. It is used to install python modules. so Django can be downloaded installed using pip install command]

Step 3: Create a Django project by running django-admin startproject myproject. A folder named myproject would be created in your current folder. You can choose any other project name.

[Explanation: django-admin startproject command is used to create necessary files required to create the website. 

The project folder contains-

  • myproject
    • __init__.py
    • asgi.py
    • setting.py
    • urls.py
    • wsgi.py
  • manage.py

A project can have multiple web apps independent or less dependent of each other. For eg. www.myecommercesite.com is the main shopping web app and www.myecommercesite/blog is the second web app for blogging.]

Step 4: Navigate to your project by running cd myproject.

[Explanation: Go inside your project to create apps and manage it.]

Step 5: Create a Django app by running django-admin startapp myapp. A folder named myapp would be created in your project folder. You can choose any other app name. 

        Your app is created. You can see your app by running python manage.py runserver in your terminal. In following steps I have explained that how to render your html file.

[Explanation: django-admin startapp  command is used to create necessary files to start a web application.

The web app folder contains-

  • migrations (folder)
  • __init__.py
  • admin.py
  • apps.py
  • models.py
  • tests.py
  • views.py

]

Step 6: Open project folder in your code editor.  VS code recommended. 

Step 7: Open setting.py which is in your project folder. (myproject/myproject/setting.py)

Step 8: Add your app name in INSTALLED_APPS list. 

[Explanation: It is not necessary to add your app in installed_apps list but recommended. 6 Apps are preinstalled by django]

INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'myapp'
]

Step 9: Add os.path.join(BASE_DIR,'templates') in 'DIRS' in TEMPLATES list.

[Explanation: It is also optional but recommended to store your templates (HTML files) in a separate folder. BASE_DIR is the path of your project directory which is then joined with a folder names templates you can use any folder name. ]

TEMPLATES = [
  {
     'BACKEND' : 'django.template.backends.django.DjangoTemplates',
     'DIRS' : [ os.path.join(BASE_DIR,'templates')],
     'APP_DIRS' : True,
     .....
  }
]

Step 10: Add following code at the end of the settings.py file and save it.

[Explanation: The following commands function similar to above. Static folder is used to store JS and CSS and media folder is for media files. MEDIA_URL is set to access the media files which would be later concatenated with urlpatterns list of urls.py file ]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'

Step 11: Add templates, media and static folder in your project folder. (myproject/templates, myproject/media, myproject/static)

[Explanation: In above steps, Path templates, static and media are set to these folders so they are created]

Step 12: Open urls.py file which is in your project folder. (myproject/myproject/urls.py) and replace with the following code. Write your app name instead of myapp.

[Explanation: In urls.py, The url patterns would be set. The default pattern is set to Django admin which is used to manage the users and models. You need to add other patterns each pattern would be connected with a function in views.py file directly or indirectly. You can create all patterns for your web apps in inside them and include the path of your urlpatterns list. It is optional to create web apps pattern separately. For example the path for urlpatterns for my web app myapp is myapp.urls so it is included. After adding all the files media path is added which is defined in step 10. MEDIA_URL is set for url and MEDIA_ROOT is set for the path to media folder]

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('myapp.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 13: Create urls.py file from your app folder. (myproject/myapp/urls.py) and add the following code. 

[Explanation:  If you have included the path for your other urlpatterns ( urlpatterns for web app) separately then create the file on the given path and write the urlpatterns. ]

from django.urls import path
from . import views
urlpatterns = [
     path('',views.index)
]

Step 14: Open views.py file from your app folder. (myproject/myapp/views.py) and add the following code. 

[Explanation: Each urlpatterns which you have set are connected to the functions in views.py file. So write those functions. The function takes request as parameter and return the response. render function is used to return a template. You can send some data also which can be used in your template. There are multiple methods to give a resonse. For eg. render, HttpResponse, redirect]

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

Step 15: Create index.html file in templates folder. (myproject/templates/index.html) and write HTML code.

[Explanation: In step 14, template index.html is set to render. In step 9, Templates path is set templates folder so index.html is created in it]

<html>
  <head>
     <title>Wecome to CODEVER</title>
  </head>
  <body>
      <h1>Thanks to learn from CODEVER<h1>
      <h2>Hope you enjoyed the tutorial. Don't forget to rate and comment.</h2>
   </body>
</html>

Step 16: Run python manage.py runserver in your terminal. The server would started on 127.0.0.1:8000 if port 8000 is not free it will select another free port.

Step 17:  Write your external css and js files inside static folder. (myproject/static). Add {%load static%} at the start of your html file. Source of file would be {%static 'index.css'%}. You use your file name instead of index.css. 

You can automate all these task by running the following python code

import os
import sys
import webbrowser


def launch(project, app):
    virtual = f'{project}-VE'
    setting = f'''


#Additional Required Setting
import os
INSTALLED_APPS+=["{app}"]
TEMPLATES[0]["DIRS"]=[os.path.join(BASE_DIR,"templates")]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"'''



    urls = f'''
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('{app}.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)'''

    urls2 = f'''
from . import views
from django.urls import path
urlpatterns = [
    path('', views.index)
]
    '''
    views = '''
from django.shortcuts import render

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

    template = '''
<html>
<head>
    <title>Wecome to CODEVER</title>
</head>
<body>
    <h1>Thanks to learn from CODEVER<h1>
    <h2>Hope you enjoyed the tutorial. Don't forget to rate and comment.</h2>
</body>
</html>
    '''


    cd = os.getcwd()
    os.system('pip install virtualenv')
    os.system(f'virtualenv {virtual}')
    os.system('call virtual\Scripts\activate')
    os.chdir(virtual)
    os.system('pip install django')
    os.system(f'django-admin startproject {project}')
    os.chdir(project)
    os.system(f'django-admin startapp {app}')
    os.system('python manage.py migrate')
    os.system('python manage.py createsuperuser --username admin')
    os.chdir(os.path.join(cd,f'{virtual}/{project}'))
    os.mkdir(os.path.join(cd,f'{virtual}/{project}/templates'))
    os.mkdir(os.path.join(cd, f'{virtual}/{project}/static'))
    os.chdir(os.path.join(cd, f'{virtual}/{project}/{project}'))
    with open('settings.py', 'a+',encoding='utf-8') as f:
        f.write(setting)
    with open('urls.py','w',encoding='utf-8') as f:
        f.write(urls)
    os.chdir(f'../{app}')
    with open('urls.py', 'w+', encoding='utf-8') as f:
        f.write(urls2)
    with open('views.py', 'w+', encoding='utf-8') as f:
        f.write(views)
    os.chdir(os.path.join(cd, f'{virtual}/{project}/templates'))
    with open('index.html','w+',encoding='utf-8') as f:
        f.write(template)
    os.chdir('..')
    webbrowser.open('http:127.0.0.1:8000')
    os.system('python manage.py runserver')


project = str(input("Your Project Name: "))
app = str(input("Your App Name: "))
launch(project, app)

Rate this post

Comments