Skip to main content

001 Python Django Application Setup From Scratch

Python Django Application Setup From Scratch
  • Create a folder
  • Activate virtual environment
conda create -n myenvname python=3.7 anaconda
activate myenvname
  • To deactivate environment anytime, use the following:
deactivate
  • Start project
django-admin startproject ProjectOne
  • Enter in the folder of the new project that is created
cd ProjectName
  • Start an app. A Django project may have one or more apps.
python manage.py startapp mainApp
  • Go back to Project Level of Folder
cd ..
  • Create Folder named 'templates' to store all templates
mkdir templates
  • Enter in the folder templates
cd templates
  • Create a folder inside 'templates' folder and name it after the app name
mkdir mainApp
  • Enter in the 'mainApp' folder
cd mainApp
  • Create a blank file named 'index.html' which will be the first page of the app
touch index.html
  • To create another webpage where some data will be displayed, we must create another html page in this folder
touch users.html

SETIINGS.PY - 3 things to do

  • Now we go to Project folder and in settings.py we will add information of where to find the templates. So open 'settings.py' in 'ProjectOne' folder
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
  • Under TEMPLATES, in 'DIRS': [] add TEMPLATE_DIR,
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  • Now, we need to also inform about the new app we built. We do that by adding app name in INSTALLED APPS list
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mainApp'
]

mainApp > models.py

  • We setup models.py to reflect columns from User database. We do this by creating a class User
frgreypan>django.db import models

# Create your models here.
class User(models.Model):
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    email = models.EmailField(max_length=256, unique=True)

mainApp > views.py

  • create views where templates will be passed on request of 'index' and 'users'. Also pass context for 'users' request including database data of users. Here is how it is done.
from django.shortcuts import render
from mainApp.models import User
# Create your views here.
def index(request):
    return render(request, 'mainApp/index.html')

def users(request):
    user_list = User.objects.order_by('first_name')
    user_dict = {'users':user_list}
    return render(request, 'mainApp/users.html', context=user_dict)
  • Create a file urls.py using command prompt. First go to project level of folder and enter mainApp folder then create 'urls.py' file
cd ..
cd ..
cd mainApp
touch urls.py
  • The following code is added to urls.py in mainApp. 
from django.conf.urls import url
from mainApp import views

urlpatterns = [
    url(r'^$', views.users, name='users'),
]

ProjectOne > urls.py

  • Now let's change project level urls.py. Here we reference users to urls.py in mainApp folder
from django.conf.urls import url, include
from django.contrib import admin
from mainApp import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('mainApp.urls'))
]

Migrate, MakeMigrations for App, and Migrate Again on command prompt

python manage.py migrate
python manage.py makemigrations mainApp
python manage.py migrate

Set up mainApp > admin.py

from django.contrib import admin
from mainApp.models import User
# Register your models here.
admin.site.register(User)
  • Run server through command prompt to see if everything is working so far
python manage.py runserver
  • Then go to http://127.0.0.1:8000 to see if you get a blank page
  • Then go to http://127.0.0.1:8000/users to see if you get a blank page
  • Then go to http://127.0.0.1:8000/admin to see if you get a login page
Add html to index.html
<!DOCTYPE html>
<html>
    <head
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <h1>Working!</h1>
    </body>
</html>
Set up super user to access django admin
  • Run the following on command prompt and fill in the details to the questions asked thereafter
python manage.py createsuperuser
  • Run the server and see http://127.0.0.1:8000/admin in browser. Login with super user.
  • Now let's populate more data in the database using fake data generating library
  • Create a file named 'populate_users.py' in the outermost ProjectOne folder
  • Add the following code in 'populate_users.py' 
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RefOne.settings")

import django
django.setup()

from mainApp.models import User
from faker import Faker

fakegen = Faker()

def populate(N=5):
    for entry in range(N):
        fake_name = fakegen.name().split()
        fake_first_name = fake_name[0]
        fake_last_name = fake_name[1]
        fake_email = fakegen.email()
        user = User.objects.get_or_create(first_name = fake_first_name,
                                          last_name = fake_last_name,
                                          email = fake_email)[0]
if __name__ == "__main__":
    print("POPULATING USERS")
    populate(20)
    print("COMPLETED POPULATING USERS")
  • This file needs to be run separately. So run the following in command prompt
python populate_users.py
  • This will create 20 users which can be seen now in admin. To see admin, run server and visit http://127.0.0.1:8000/admin
  • Let's prepare user.html template inside templates > mainApp
templates > mainApp > users.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Users</title>
    </head>
    <body>
        <h1>Users</h1>
            {% if users %}
                <table>
                    <thead>
                        <th>Email</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </thead>
                    {% for user in users %}
                        <tr>
                            <td>{{user.first_name}}</td>
                            <td>{{user.last_name}}</td>
                            <td>{{user.email}}</td>
                        </tr>
                    {% endfor %}
                </table>
            {% else %}
                <p>NOT FOUND</p>
            {% endif %}
    </body>
</html>

CSS

  • Now let's add CSS
  • We will do that using Static folder
  • Create a folder named 'static' in the outermost Project folder
  • create another folder inside static and name it 'css'
  • Inside this folder create a file named mystyle.css
  • In this file add the following code:
h1 {
    color: red;
}
td {
    border-right: 1px dotted red;
}
  • Open settings.py in Project folder
  • Add the following line
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# Create STATIC_DIR variable storing path to 'static' directory
STATIC_DIR = os.path.join(BASE_DIR, "static")
  • At the very bottom of settings.py add the following line
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
  • Now run server and see the css working.
  • That is how an application is set up in Django

Comments

Popular posts from this blog

Python - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

Difference between .exec() and .execPopulate() in Mongoose?

Here I answer what is the difference between .exec() and .execPopulate() in Mongoose? .exec() is used with a query while .execPopulate() is used with a document Syntax for .exec() is as follows: Model.query() . populate ( 'field' ) . exec () // returns promise . then ( function ( document ) { console . log ( document ); }); Syntax for .execPopulate() is as follows: fetchedDocument . populate ( 'field' ) . execPopulate () // returns promise . then ( function ( document ) { console . log ( document ); }); When working with individual document use .execPopulate(), for model query use .exec(). Both returns a promise. One can do without .exec() or .execPopulate() but then has to pass a callback in populate.

683 K Empty Slots

  Approach #1: Insert Into Sorted Structure [Accepted] Intuition Let's add flowers in the order they bloom. When each flower blooms, we check it's neighbors to see if they can satisfy the condition with the current flower. Algorithm We'll maintain  active , a sorted data structure containing every flower that has currently bloomed. When we add a flower to  active , we should check it's lower and higher neighbors. If some neighbor satisfies the condition, we know the condition occurred first on this day. Complexity Analysis Time Complexity (Java):  O(N \log N) O ( N lo g N ) , where  N N  is the length of  flowers . Every insertion and search is  O(\log N) O ( lo g N ) . Time Complexity (Python):  O(N^2) O ( N 2 ) . As above, except  list.insert  is  O(N) O ( N ) . Space Complexity:  O(N) O ( N ) , the size of  active . Approach #2: Min Queue [Accepted] Intuition For each contiguous block ("window") of  k  po...