CREATING PROJECT
django-admin startproject projectname
eg:django-admin startproject myproject
cd myproject
myproject/
manage.py
myproject/
init.py
settings.py
urls.py
wsgi.py
settings.py
DEBUG = True
for sqlite3
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3’,
‘NAME’: os.path.join(BASE_DIR, ‘db.sqlite3’),
}
}
for mysql
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘databasename’,
‘USER’: ‘root’,
‘PASSWORD’: ”,
‘HOST’: ‘localhost’,
‘PORT’: ”,
}
}
to check if project is working
cd projectname
eg: cd myproject
python manage.py runserver
Starting development server at http://127.0.0.1:8000/
APPS LIFECYCLE
python manage.py startapp appname
eg:python manage.py startapp myapp
myapp/
init.py
admin.py
models.py
tests.py
views.py
create a python file in myapp
eg: appurls.py
then,
myapp/
init.py
admin.py
models.py
apps.py
tests.py
views.py
appurls.py
settings.py
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘myapp’
]
myproject/urls.py
from django.conf.urls import url,include
from django.contrib import admin
import myapp.appurls
urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^myapp/’, include(myapp.appurls)),
]
ADMIN INTERFACE
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Starting development server at http://127.0.0.1:8000
in browser: /admin/
CREATING VIEWS & URL MAPPING
views.py
from django.http import HttpResponse
Create your views here.
def index(request):
return HttpResponse(‘Hello World’)
myapp/appurls.py
from django.conf.urls import url
from.import views
urlpatterns = [
url(‘index/’,views.index,name=’index’)
]
myproject/urls.py
from django.conf.urls import url,include
from django.contrib import admin
import myapp.appurls
urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(‘myapp/’, include(myapp.appurls))
]
python manage.py runserver
#
views.py
from django.http import HttpResponse
def hello(request):
text = “””<h1>welcome to my app !</h1>”””
return HttpResponse(text)
myapp/appurls.py
urlpatterns = [
url(‘hello/’,views.hello, name=’hello’),
]
#
Dynamic Content with view
views.py
import datetime
def getcurrentdate(request):
now = datetime.datetime.now()
html=”<html><body>It is %s now.</body></html>”%now
return HttpResponse(html)
myapp/appurls.py
from django.conf.urls import url
from.import views
urlpatterns = [
url(‘index/’,views.index, name=’index’),
url(‘date/’,views.getcurrentdate, name=’getcurrentdate’)
]
#
Sending Parameters to views
views.py
from django.http import HttpResponse
def viewArticle(request, articleId):
text = “Displaying article Number :%s”%articleId
return HttpResponse(text)
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(r’^article/(\d+)/’, views.viewArticle, name=’article’),
]
to pass month and year
views.py
def viewArticles(request, month, year):
text = “Displaying articles of : %s/%s”%(year, month)
return HttpResponse(text)
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(r’^articles/(\d{2})/(\d{4})’, views.viewArticles, name=’articles’), ]
DJANGO TEMPLATE SYSTEM
create a folder ‘template’ inside project folder to hold html files.
settings.py
under BASE_DIR type
TEMPLATE_DIR = os.path.join(BASE_DIR,’template’)
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’,
],
},
},
]
in templates folder create html file
eg: hello.html
<html>
<body>Hello World!!!<p>Today is {{today}}</body> </html>
views.py
def hello(request):
today = datetime.datetime.now().date()
return render(request, “hello.html”, {“today” : today})
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(‘hello/’,views.hello, name=’hello’), ]
Filters
eg: one.html
<html>
<body>The blog is about Artificial Intelligence:>It is truncated
as below:{{stri|truncatewords:10}}
<p>Lowercase string is: {{stri|lower}}</p>
<p>Escape linebreaks : {{stri|escape|linebreaks}}</p>
</body> </html>
views.py
def blogs(request):
stri = ”’Artificial Intelligence(AI) is the future. It is shaping many industries
even when it’s new compared to other technologies. AI is also growing as
scientists and engineers are doing research at a rapid pace.
Companies such as Google, Facebook, Microsoft, and others are also investing
heavily in AI research, and the results are quite evident. The release of
self-driving cars is just an example of rapid
return render(request, “one.html”, {“stri” : stri})
AI growth.”’
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(‘blogs/’,views.blogs, name=’blogs’), ]
Tag if
two.html
<html>
<body>
Hello World!!!<p>Today is {{today}}</p>
It is :
{% if today.day == 1 %}
the first day of month.
{% elif today.day == 30 %}
the last day of month.
{% else %}
I don’t know.
{% endif %}
<p>
</body>
</html>
views.py
def hello1(request):
today = datetime.datetime.now().date()
return render(request, “two.html”, {“today” : today})
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(‘ifs/’,views.hello1, name=’hello1′), ]
Tag For
views.py
def fortag(request):
today = datetime.datetime.now().date()
daysOfWeek = [‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’]
return render(request, “three.html”,{“days_of_week”:daysOfWeek,
”today”:today})
three.html
<html>
<body>
Today is {{today}}
Hello World!!!<p>The days of week are </p>
<p>
{% for day in days_of_week %}
{{day}}
</p>
{% endfor %}
</body>
</html>
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(‘fors/’,views.fortag, name=’fortag’), ]
Block and Extend Tags
main_template.html
<html>
<head><title>{% block title %}#Page Title{% endblock %}</title>
<body>
{% block content %}
Body content
{% endblock %}
</body>
</html>
child.html
{% extends “main_template.html” %}
{% block title %}My Hello Page{% endblock %}
{% block content %}
This is the content page of child template.
It inherits html elements of parent html.
{% endblock %}
views.py
def child(request):
return render(request, “child.html”)
myapp/appurls.py
from django.conf.urls import url
urlpatterns =[
url(child/’,views.child, name=child), ]
Comment Tags
SingleLine Comment: {# comment #}
MultiLine Comment {% comment %}
comment statements here
{% endcomment %}