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
Post a Comment