SlideShare a Scribd company logo
1 of 52
zekeLabs
Discovering Django
Learning made Simpler !
www.zekeLabs.com
Introduction
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Introduction to Django
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● It is a web framework for developing scalable, secure and maintainable applications.
● It is based on MVC pattern with a slight difference in naming. The view is referred as template
and controller is referred as view in Django so it is MTV.
● It officially supports following databases – PostgreSQL, MySQL, SQLite, Oracle.
● It helps in faster developments.
● It is written on the powerful language Python.
● It can be used for high load projects. For eg, Instagram and Pinterest.
Django Structure
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Installation
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Install Python
https://www.python.org/downloads/
● Install virtualenv package (It provides isolated Python environments, which are more practical
than installing packages systemwide)
pip install virtualenv
● Create a new Virtual environment
virtualenv {your-venv-name}
● Activate Virtual environment
{your-venv-name} -> Scripts -> activate
● Install Django
pip install django
Setup new Django Project
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Create a new project
django-admin startproject {project-name}
● Start new application
python manage.py startapp {app-name}
add it in settings.py
● Start server
python manage.py runserver
Model Layer
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Models
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● It contains the essential fields and behaviors of the data.
● Each model is a Python class and also a sub-class of django.db.models.Model
● Each model represents a table in the database.
● Each field represents a column in the table.
● Each field has a field type which can be any of the following.
- CharField, TextField
- IntegerField, FloatField, DecimalField
- DateField , TimeField, DateTimeField
- EmailField, URLField
- ForeignKey, ManyToManyField and many more.
Create Model
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Blog Model Example,
from django.db import models
class Blog(models.Model):
status_choices = (
(‘D’, ‘Draft’),
(‘P’, ‘Published’)
)
title = models.CharField(max_length=100)
description = models.TextField()
status = models.CharField(max_length=1, choices = status_choices)
def __str__(self):
return self.title
Migrations
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Migrations are how Django stores changes made to the database schema/models.
● The migration files can be found inside migrations directory in your app directory.
● Following command tells Django that you made changes to your models
python manage.py makemigrations {appname}
● Following command take latest migration file and updates database
python manage.py migrate {appname}
Create Model Instance
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Run Python Interactive Shell
python manage.py shell
● Import model. For eg,
from myapp.models import Blog
● Create new Blog object. For eg,
b1 = Blog(…)
b1.save()
Query Data From DB
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Run Python Interactive Shell
python manage.py shell
● Import model. For eg,
from myapp.models import Blog
● Get all from DB. For eg,
all_blogs = Blog.objects.all()
● Objects is the manager. The manager takes care of all table level operations including data
lookup.
Data Lookup: filter()
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Filter returns a QuerySet.
● For eg,
blog_with_title = Blog.objects.filter(title=‘some title’)
blog_multiple_search_param = Blog.objects.filter(title=‘title’, status=‘D’)
blog_title_containing_text = Blog.objects.filter(title__contains=‘some text’)
blog_title_containing_text_case_insensitive = Blog.objects.filter(title__icontains=‘text’)
blog_title_starts_with = Blog.objects.filter(title__startswith=‘starting text’)
blog_title_ends_with = Blog.objects.filter(title__endswith=‘ending text’)
Data Lookup: get()
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Get() returns a single object.
● For eg,
blog_with_id = Blog.objects.get(id=‘2’)
● Exception incase of multiple objects returned. For eg,
blog_multiple_results = Blog.objects.get(title__contains=‘some text’)
● Exception incase no results found. For eg,
blog_no_results = Blog.objects.get(title=‘some text’)
Data Lookup: order-by()
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● We can get the resulting QuerySet in a specific order.
● Order-by title. For eg,
blog_by_title = Blog.objects.order_by(‘title’)
● Reverse order-by title. For eg,
blog_by_title = Blog.objects.order_by(‘-title’)
● Add default order-by in model. For eg,
class Blog(models.Model);
------------------------
class Meta:
ordering = [‘-id’]
Chaining & Slicing
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● We can chain multiple lookups to get required data.
● For eg,
blog_chain_lookup = Blog.objects.filter(title__contains=“Blog”).order_by(“title”)
● We use slicing to get limited number of result.
● For eg,
blog_first = Blog.objects.all()[0]
blog_first_five = Blog.objects.all()[0:5]
blog_last = Blog.objects.order_by(‘-id’)[0]
Update Data
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Method 1:
blog = Blog.objects.get(id=1)
blog.title = “Updated Title Blog 1”
blog.save()
● Method 2 (Better Performance):
Blog.objects.filter(id=1).update(title=“Updated Title Blog 1”)
● Update multiple row:
Blog.objects.filter(status=‘D’).update(status=‘P’)
Delete Data
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● To delete data we can simple call delete().
● For eg,
blog = Blog.objects.get(id=3)
blog.delete()
● We can also delete multiple rows. For eg,
Blog.objects.filter(status=‘D’).delete()
● We can also delete all rows. For eg,
Blog.objects.all().delete()
View Layer
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Views
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● View is the Business Logic Layer.
● It fetches data from your database and delivers it to a template.
● It decides what data needs to be sent to the templates.
● It handles the data received by user interactions and internal processes.
● Each view handles a specific function.
● A view can either be a Python function or a class.
Writing Our First View
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Below are some function based view.
from django.http import HttpResponse
def index(request): // prints “Hello World” on the browser
return HttpResponse(“Hello World”)
def details(request, id): prints blog object label for the given id
blog = Blog.objects.get(id=id)
return HttpResponse(blog)
Mapping our first URL
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● URLConf
from django.conf.urls import url
from blogapp.views import index
urlpatterns = [
….
url(r'^$', index),
url(r’^details/(?P<id>[-w]+)/$)’, details),
url(r’^review/(?P<year>[0-9]{4})/(?P<mon>[0-9]{2})/$’, reviews)
]
● For eg,
“details/1/” => details(request, id=1)
“reviews/2018/08/” => reviews(request, year=2018, mon=08)
Template Layer
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Templates
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● This is the display logic layer.
● It separates application data from the way it is presented.
● These are mostly HTML files for presenting application data in web browser.
● The HTML template holds template tags to populate the data passed from views.
Writing our first Template
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Create a directory /templates
● Create a file “index.html”
● Add following code in it:
<html>
<head><title>First Django Template</title></head>
<body>
<h1>Welcome {{ name }}</h1>
</body>
</html>
Note: The value for template variable {{ name }} is passed from view
Writing View For The Previous Template
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Add the following view:
from django.shortcuts import render
def welcome(request):
context = {
“name”: “Qaifi Khan”
}
return render(request, “index.html”, context)
● Visit settings.py and add the templates directory:
TEMPLATES = [
{
'DIRS': ['templates’],
}
]
Some Template Tags: If-elif
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
{% if age_more_than_18 and age_less_than_28%}
<p>Age 18-28</p>
{% elif age_less_than_38 or age_more_than_48%}
<p>Age 28-38 or more than 48</p>
{% elif not eligible %}
<p>Not eligible</p>
{% elif “xy” in “wxyz” %}
<p>In wxyz</p>
{% else %}
<p>Else</p>
{% endif %}
Some Template Tags: for
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
<ul>
{% for blog in blog_list reversed %}
<li>{{ forloop.counter }} : {{ blog.title }}</li>
{% empty %}
<p>No blogs found</p>
{% endfor %}
</ul>
//forloop.counter starts with 1
//forloop.counter0 starts with 0
//forloop.revcounter starts with last but is 1-indexed
//forloop.revcounter0 starts with last but is 0-indexed
Admin
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Admin Site
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Django provides a built-in admin panel.
● You can perform all CRUD operations on your database.
● We can control which models are accessible from Admin panel.
● To access admin panel we need to create a super user.
● Follow these steps to create a super user.
- In command prompt type “python manage.py createsuperuser”
- Enter username, email, password and confirm password.
- Start development server again and visit admin panel
- Input login credentials and login
Adding a Model for Access in Admin Panel
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Open admin.py in the application directory
● Add the following code:
from .models import {model_name}
admin.site.register(model_name)
Showing More Data in List Display
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● You can control the fields visible in list display section.
● For that we need to create a ModelAdmin. Let’s do that.
class BlogAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘status’)
……
admin.site.register(Admin, BlogAdmin)
Adding a Search Bar
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● To add a search bar we need to Edit the ModelAdmin.
● Make following changes
class BlogAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘status’)
search_fields = (‘title’)
……
admin.site.register(Admin, BlogAdmin)
Adding Filters
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● To add filter functionality we need to Edit the ModelAdmin.
● Make following changes
class BlogAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘status’)
search_fields = (‘title’,)
list_filter = (‘status’,)
……
admin.site.register(Admin, BlogAdmin)
Customizing Edit Form
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● We can also customize the Edit Form.
● To specify what all fields are editable, pass a list in fields as shown below.
class BlogAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘status’)
search_fields = (‘title’,)
list_filter = (‘status’)
fields = (‘title’, ‘description’)
……
admin.site.register(Admin, BlogAdmin)
Forms
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Let’s Create a Basic Form GET Request
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Create HTML form:
<form action=‘/search/’ method=“get”>
<input type=“text” placeholder=“Enter Search String” name=“q”/>
<input type=“submit” value=“Search” />
</form>
● Create request URL:
url(r’^search/$’, search)
Basic Form GET Request Continued…
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Handling at View:
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.’
return HttpResponse(message)
Using Django’s Form Class
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Django provides us with a “Form” library to manage everything from form display to validation.
● We need to define one form class for each HTML form required by us. So let’s start.
● Create a new file form.py. Add following code:
from django import forms
STATUS_CHOICES = ((‘D’, ‘Draft’), (‘P’, ‘Published’))
class CreatePostForm(forms.Form):
title = forms.CharField()
description = forms.CharField(widget=forms.Textarea())
status = form.ChoiceField(widget=forms.Select(), choices= STATUS_CHOICES)
Using Django’s Form Class Continued…
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Add following in view.py
from blogapp.forms import CreatePostForm
def create_post(request):
if request.method == ‘POST’:
form = CreatePostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
blog = Blog(title = cd[‘title’],
description = cd[‘descripition’],
status = cd[‘status’])
else:
form = CreatePostForm()
return render(request, ‘create_post.html’, {‘form’: form})
Adding Validation
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Make following changes in CreatePostForm class:
from django import forms
STATUS_CHOICES = ((‘D’, ‘Draft’), (‘P’, ‘Published’))
class CreatePostForm(forms.Form):
title = forms.CharField(max_length=100, required=True)
description = forms.CharField(widget=forms.Textarea() , required=True)
status = form.ChoiceField(widget=forms.Select(), choices= STATUS_CHOICES)
Adding Custom Validation
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Make following changes in CreatePostForm class:
class CreatePostForm(forms.Form):
…..
def clean_description(self):
description = self.cleaned_data[‘description’]
num_words = len(description.split(‘ ‘))
if num_words < 3:
raise forms.ValidationError("Not enough words!")
return description
● Note: Django automatically call any method starting with “clean_” during validation.
Model Forms
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Sometime we just need a form for a predefined model. In that case we can simply use
ModelForm. Let’s start.
● Add following code in forms.py
from django.forms import ModelForm
from .models import Blog
class CreateBlogModelForm(ModelForm):
class Meta:
model = Blog
fields = [‘title’, ‘description’]
//exclude = [‘status’]
Overriding Labels, HelpText, Widgets, HelpText etc in ModelForm
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Make following changes in the code:
class CreateBlogModelForm(ModelForm):
class Meta:
……
labels = {
‘title’: ‘Blog Title’,
‘description’: ‘Blog Description’}
widgets = {
description: Textarea()}
Adding Custom Validation in ModelForm
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Make following changes in CreatePostForm class:
class CreateBlogModelForm(ModelForm):
def clean_description(self):
description = self.cleaned_data[‘description’]
num_words = len(description.split(‘ ‘))
if num_words < 3:
raise forms.ValidationError("Not enough words!")
return description
class Meta:
……..
● Note: Django automatically call any method starting with “clean_” during validation.
Upload an Image
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Configure MEDIA_ROOT and MEDIA_URL in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, '/media/’) //Path where file stores
MEDIA_URL = '/media/’ //Browser URL to access file
● Configure MEDIA_ROOT and MEDIA_URL in settings.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
……
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upload an Image Continued…
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Make following changes in forms.py
class CreatePostForm(forms.Form):
……
image = forms.FileField()
● Make following changes in views.py
def create_post(request):
form = CreatePostForm(request.POST, request.FILES)
Blog(image = cleaned_data[‘image’])
● Make following changes in HTML file
<….. enctype="multipart/form-data">
Development Process
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
Settings
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Django provides with a default settings file.
● We can create our own settings file as well.
● In case there are multiple settings file, we need to tell Django which file to use. For this we can
use the environment variable DJANGO_SETTINGS_MODULE.
export/set DJANGO_SETTINGS_MODULE=myproj.settings
● We can use settings variables in our code as well. For eg,
from django.conf import settings
if settings.DEBUG:
………..
Exceptions
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Django raises some of its own exceptions as well as standard Python exceptions.
● Some Django exceptions are:
● ObjectDoesNotExist: raised when object not found for a query.
● FieldDoesNotExist: raised when a requested field doesn’t exist.
● MultipleObjectsReturned: raised when query returns multiple object but only one was expected.
● ViewDoesNotExist: raised when requested view doesn’t exist for a url.
● FieldError: raised when there is a problem with a model field.
● ValidationError: raised when data is not what was expected in the form.
And many more…
Django-admin and manage.py
support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
● Both perform the same task except manage.py sets DJANGO_SETTINGS_MODULE
environment variable to the project’s settings file.
● Syntax:
django-admin <command> [options]
manage.py <command> [options]
● For eg,
django-admin makemigrations {app_name}
django-admin migrate {app_name}
django-admin runserver
django-admin shell
Thank You !!!

More Related Content

What's hot

Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationSociable
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and EasybIakiv Kramarenko
 
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan ChepurnyiFixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan ChepurnyiMeet Magento Spain
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridgeRomans Malinovskis
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateThorben Janssen
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Oren Rubin
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React PerformanceChing Ting Wu
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Django ORM - Marcin Markiewicz
Django ORM - Marcin Markiewicz Django ORM - Marcin Markiewicz
Django ORM - Marcin Markiewicz Sunscrapers
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Robert DeLuca
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryAlek Davis
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 

What's hot (20)

Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and Easyb
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan ChepurnyiFixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan Chepurnyi
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 
CDI 2.0 Deep Dive
CDI 2.0 Deep DiveCDI 2.0 Deep Dive
CDI 2.0 Deep Dive
 
Django ORM - Marcin Markiewicz
Django ORM - Marcin Markiewicz Django ORM - Marcin Markiewicz
Django ORM - Marcin Markiewicz
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 

Similar to Discovering Django - zekeLabs

Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django FrameworkRicardo Soares
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the WildDavid Glick
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15Asika Kuo
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 

Similar to Discovering Django - zekeLabs (20)

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
templates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtratemplates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtra
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15
 
Django crush course
Django crush course Django crush course
Django crush course
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 

More from zekeLabs Technologies

Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...
Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...
Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...zekeLabs Technologies
 
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabs
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabsDesign Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabs
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabszekeLabs Technologies
 
[Webinar] Following the Agile Footprint - zekeLabs
[Webinar] Following the Agile Footprint - zekeLabs[Webinar] Following the Agile Footprint - zekeLabs
[Webinar] Following the Agile Footprint - zekeLabszekeLabs Technologies
 
Machine learning at scale - Webinar By zekeLabs
Machine learning at scale - Webinar By zekeLabsMachine learning at scale - Webinar By zekeLabs
Machine learning at scale - Webinar By zekeLabszekeLabs Technologies
 
A curtain-raiser to the container world Docker & Kubernetes
A curtain-raiser to the container world Docker & KubernetesA curtain-raiser to the container world Docker & Kubernetes
A curtain-raiser to the container world Docker & KuberneteszekeLabs Technologies
 
Docker - A curtain raiser to the Container world
Docker - A curtain raiser to the Container worldDocker - A curtain raiser to the Container world
Docker - A curtain raiser to the Container worldzekeLabs Technologies
 
Master guide to become a data scientist
Master guide to become a data scientist Master guide to become a data scientist
Master guide to become a data scientist zekeLabs Technologies
 

More from zekeLabs Technologies (20)

Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...
Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...
Webinar - Build Cloud-native platform using Docker, Kubernetes, Prometheus, I...
 
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabs
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabsDesign Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabs
Design Patterns for Pods and Containers in Kubernetes - Webinar by zekeLabs
 
[Webinar] Following the Agile Footprint - zekeLabs
[Webinar] Following the Agile Footprint - zekeLabs[Webinar] Following the Agile Footprint - zekeLabs
[Webinar] Following the Agile Footprint - zekeLabs
 
Machine learning at scale - Webinar By zekeLabs
Machine learning at scale - Webinar By zekeLabsMachine learning at scale - Webinar By zekeLabs
Machine learning at scale - Webinar By zekeLabs
 
A curtain-raiser to the container world Docker & Kubernetes
A curtain-raiser to the container world Docker & KubernetesA curtain-raiser to the container world Docker & Kubernetes
A curtain-raiser to the container world Docker & Kubernetes
 
Docker - A curtain raiser to the Container world
Docker - A curtain raiser to the Container worldDocker - A curtain raiser to the Container world
Docker - A curtain raiser to the Container world
 
Serverless and cloud computing
Serverless and cloud computingServerless and cloud computing
Serverless and cloud computing
 
SQL
SQLSQL
SQL
 
02 terraform core concepts
02 terraform core concepts02 terraform core concepts
02 terraform core concepts
 
08 Terraform: Provisioners
08 Terraform: Provisioners08 Terraform: Provisioners
08 Terraform: Provisioners
 
Outlier detection handling
Outlier detection handlingOutlier detection handling
Outlier detection handling
 
Nearest neighbors
Nearest neighborsNearest neighbors
Nearest neighbors
 
Naive bayes
Naive bayesNaive bayes
Naive bayes
 
Master guide to become a data scientist
Master guide to become a data scientist Master guide to become a data scientist
Master guide to become a data scientist
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Linear models of classification
Linear models of classificationLinear models of classification
Linear models of classification
 
Grid search, pipeline, featureunion
Grid search, pipeline, featureunionGrid search, pipeline, featureunion
Grid search, pipeline, featureunion
 
Feature selection
Feature selectionFeature selection
Feature selection
 
Essential NumPy
Essential NumPyEssential NumPy
Essential NumPy
 
Ensemble methods
Ensemble methods Ensemble methods
Ensemble methods
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Discovering Django - zekeLabs

  • 1. zekeLabs Discovering Django Learning made Simpler ! www.zekeLabs.com
  • 3. Introduction to Django support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● It is a web framework for developing scalable, secure and maintainable applications. ● It is based on MVC pattern with a slight difference in naming. The view is referred as template and controller is referred as view in Django so it is MTV. ● It officially supports following databases – PostgreSQL, MySQL, SQLite, Oracle. ● It helps in faster developments. ● It is written on the powerful language Python. ● It can be used for high load projects. For eg, Instagram and Pinterest.
  • 4. Django Structure support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
  • 5. Installation support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Install Python https://www.python.org/downloads/ ● Install virtualenv package (It provides isolated Python environments, which are more practical than installing packages systemwide) pip install virtualenv ● Create a new Virtual environment virtualenv {your-venv-name} ● Activate Virtual environment {your-venv-name} -> Scripts -> activate ● Install Django pip install django
  • 6. Setup new Django Project support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Create a new project django-admin startproject {project-name} ● Start new application python manage.py startapp {app-name} add it in settings.py ● Start server python manage.py runserver
  • 7. Model Layer support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
  • 8. Models support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● It contains the essential fields and behaviors of the data. ● Each model is a Python class and also a sub-class of django.db.models.Model ● Each model represents a table in the database. ● Each field represents a column in the table. ● Each field has a field type which can be any of the following. - CharField, TextField - IntegerField, FloatField, DecimalField - DateField , TimeField, DateTimeField - EmailField, URLField - ForeignKey, ManyToManyField and many more.
  • 9. Create Model support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Blog Model Example, from django.db import models class Blog(models.Model): status_choices = ( (‘D’, ‘Draft’), (‘P’, ‘Published’) ) title = models.CharField(max_length=100) description = models.TextField() status = models.CharField(max_length=1, choices = status_choices) def __str__(self): return self.title
  • 10. Migrations support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Migrations are how Django stores changes made to the database schema/models. ● The migration files can be found inside migrations directory in your app directory. ● Following command tells Django that you made changes to your models python manage.py makemigrations {appname} ● Following command take latest migration file and updates database python manage.py migrate {appname}
  • 11. Create Model Instance support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Run Python Interactive Shell python manage.py shell ● Import model. For eg, from myapp.models import Blog ● Create new Blog object. For eg, b1 = Blog(…) b1.save()
  • 12. Query Data From DB support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Run Python Interactive Shell python manage.py shell ● Import model. For eg, from myapp.models import Blog ● Get all from DB. For eg, all_blogs = Blog.objects.all() ● Objects is the manager. The manager takes care of all table level operations including data lookup.
  • 13. Data Lookup: filter() support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Filter returns a QuerySet. ● For eg, blog_with_title = Blog.objects.filter(title=‘some title’) blog_multiple_search_param = Blog.objects.filter(title=‘title’, status=‘D’) blog_title_containing_text = Blog.objects.filter(title__contains=‘some text’) blog_title_containing_text_case_insensitive = Blog.objects.filter(title__icontains=‘text’) blog_title_starts_with = Blog.objects.filter(title__startswith=‘starting text’) blog_title_ends_with = Blog.objects.filter(title__endswith=‘ending text’)
  • 14. Data Lookup: get() support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Get() returns a single object. ● For eg, blog_with_id = Blog.objects.get(id=‘2’) ● Exception incase of multiple objects returned. For eg, blog_multiple_results = Blog.objects.get(title__contains=‘some text’) ● Exception incase no results found. For eg, blog_no_results = Blog.objects.get(title=‘some text’)
  • 15. Data Lookup: order-by() support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● We can get the resulting QuerySet in a specific order. ● Order-by title. For eg, blog_by_title = Blog.objects.order_by(‘title’) ● Reverse order-by title. For eg, blog_by_title = Blog.objects.order_by(‘-title’) ● Add default order-by in model. For eg, class Blog(models.Model); ------------------------ class Meta: ordering = [‘-id’]
  • 16. Chaining & Slicing support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● We can chain multiple lookups to get required data. ● For eg, blog_chain_lookup = Blog.objects.filter(title__contains=“Blog”).order_by(“title”) ● We use slicing to get limited number of result. ● For eg, blog_first = Blog.objects.all()[0] blog_first_five = Blog.objects.all()[0:5] blog_last = Blog.objects.order_by(‘-id’)[0]
  • 17. Update Data support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Method 1: blog = Blog.objects.get(id=1) blog.title = “Updated Title Blog 1” blog.save() ● Method 2 (Better Performance): Blog.objects.filter(id=1).update(title=“Updated Title Blog 1”) ● Update multiple row: Blog.objects.filter(status=‘D’).update(status=‘P’)
  • 18. Delete Data support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● To delete data we can simple call delete(). ● For eg, blog = Blog.objects.get(id=3) blog.delete() ● We can also delete multiple rows. For eg, Blog.objects.filter(status=‘D’).delete() ● We can also delete all rows. For eg, Blog.objects.all().delete()
  • 19. View Layer support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
  • 20. Views support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● View is the Business Logic Layer. ● It fetches data from your database and delivers it to a template. ● It decides what data needs to be sent to the templates. ● It handles the data received by user interactions and internal processes. ● Each view handles a specific function. ● A view can either be a Python function or a class.
  • 21. Writing Our First View support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Below are some function based view. from django.http import HttpResponse def index(request): // prints “Hello World” on the browser return HttpResponse(“Hello World”) def details(request, id): prints blog object label for the given id blog = Blog.objects.get(id=id) return HttpResponse(blog)
  • 22. Mapping our first URL support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● URLConf from django.conf.urls import url from blogapp.views import index urlpatterns = [ …. url(r'^$', index), url(r’^details/(?P<id>[-w]+)/$)’, details), url(r’^review/(?P<year>[0-9]{4})/(?P<mon>[0-9]{2})/$’, reviews) ] ● For eg, “details/1/” => details(request, id=1) “reviews/2018/08/” => reviews(request, year=2018, mon=08)
  • 23. Template Layer support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
  • 24. Templates support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● This is the display logic layer. ● It separates application data from the way it is presented. ● These are mostly HTML files for presenting application data in web browser. ● The HTML template holds template tags to populate the data passed from views.
  • 25. Writing our first Template support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Create a directory /templates ● Create a file “index.html” ● Add following code in it: <html> <head><title>First Django Template</title></head> <body> <h1>Welcome {{ name }}</h1> </body> </html> Note: The value for template variable {{ name }} is passed from view
  • 26. Writing View For The Previous Template support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Add the following view: from django.shortcuts import render def welcome(request): context = { “name”: “Qaifi Khan” } return render(request, “index.html”, context) ● Visit settings.py and add the templates directory: TEMPLATES = [ { 'DIRS': ['templates’], } ]
  • 27. Some Template Tags: If-elif support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 {% if age_more_than_18 and age_less_than_28%} <p>Age 18-28</p> {% elif age_less_than_38 or age_more_than_48%} <p>Age 28-38 or more than 48</p> {% elif not eligible %} <p>Not eligible</p> {% elif “xy” in “wxyz” %} <p>In wxyz</p> {% else %} <p>Else</p> {% endif %}
  • 28. Some Template Tags: for support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 <ul> {% for blog in blog_list reversed %} <li>{{ forloop.counter }} : {{ blog.title }}</li> {% empty %} <p>No blogs found</p> {% endfor %} </ul> //forloop.counter starts with 1 //forloop.counter0 starts with 0 //forloop.revcounter starts with last but is 1-indexed //forloop.revcounter0 starts with last but is 0-indexed
  • 30. Admin Site support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Django provides a built-in admin panel. ● You can perform all CRUD operations on your database. ● We can control which models are accessible from Admin panel. ● To access admin panel we need to create a super user. ● Follow these steps to create a super user. - In command prompt type “python manage.py createsuperuser” - Enter username, email, password and confirm password. - Start development server again and visit admin panel - Input login credentials and login
  • 31. Adding a Model for Access in Admin Panel support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Open admin.py in the application directory ● Add the following code: from .models import {model_name} admin.site.register(model_name)
  • 32. Showing More Data in List Display support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● You can control the fields visible in list display section. ● For that we need to create a ModelAdmin. Let’s do that. class BlogAdmin(admin.ModelAdmin): list_display = (‘title’, ‘status’) …… admin.site.register(Admin, BlogAdmin)
  • 33. Adding a Search Bar support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● To add a search bar we need to Edit the ModelAdmin. ● Make following changes class BlogAdmin(admin.ModelAdmin): list_display = (‘title’, ‘status’) search_fields = (‘title’) …… admin.site.register(Admin, BlogAdmin)
  • 34. Adding Filters support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● To add filter functionality we need to Edit the ModelAdmin. ● Make following changes class BlogAdmin(admin.ModelAdmin): list_display = (‘title’, ‘status’) search_fields = (‘title’,) list_filter = (‘status’,) …… admin.site.register(Admin, BlogAdmin)
  • 35. Customizing Edit Form support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● We can also customize the Edit Form. ● To specify what all fields are editable, pass a list in fields as shown below. class BlogAdmin(admin.ModelAdmin): list_display = (‘title’, ‘status’) search_fields = (‘title’,) list_filter = (‘status’) fields = (‘title’, ‘description’) …… admin.site.register(Admin, BlogAdmin)
  • 37. Let’s Create a Basic Form GET Request support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Create HTML form: <form action=‘/search/’ method=“get”> <input type=“text” placeholder=“Enter Search String” name=“q”/> <input type=“submit” value=“Search” /> </form> ● Create request URL: url(r’^search/$’, search)
  • 38. Basic Form GET Request Continued… support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Handling at View: def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q'] else: message = 'You submitted an empty form.’ return HttpResponse(message)
  • 39. Using Django’s Form Class support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Django provides us with a “Form” library to manage everything from form display to validation. ● We need to define one form class for each HTML form required by us. So let’s start. ● Create a new file form.py. Add following code: from django import forms STATUS_CHOICES = ((‘D’, ‘Draft’), (‘P’, ‘Published’)) class CreatePostForm(forms.Form): title = forms.CharField() description = forms.CharField(widget=forms.Textarea()) status = form.ChoiceField(widget=forms.Select(), choices= STATUS_CHOICES)
  • 40. Using Django’s Form Class Continued… support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Add following in view.py from blogapp.forms import CreatePostForm def create_post(request): if request.method == ‘POST’: form = CreatePostForm(request.POST) if form.is_valid(): cd = form.cleaned_data blog = Blog(title = cd[‘title’], description = cd[‘descripition’], status = cd[‘status’]) else: form = CreatePostForm() return render(request, ‘create_post.html’, {‘form’: form})
  • 41. Adding Validation support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Make following changes in CreatePostForm class: from django import forms STATUS_CHOICES = ((‘D’, ‘Draft’), (‘P’, ‘Published’)) class CreatePostForm(forms.Form): title = forms.CharField(max_length=100, required=True) description = forms.CharField(widget=forms.Textarea() , required=True) status = form.ChoiceField(widget=forms.Select(), choices= STATUS_CHOICES)
  • 42. Adding Custom Validation support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Make following changes in CreatePostForm class: class CreatePostForm(forms.Form): ….. def clean_description(self): description = self.cleaned_data[‘description’] num_words = len(description.split(‘ ‘)) if num_words < 3: raise forms.ValidationError("Not enough words!") return description ● Note: Django automatically call any method starting with “clean_” during validation.
  • 43. Model Forms support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Sometime we just need a form for a predefined model. In that case we can simply use ModelForm. Let’s start. ● Add following code in forms.py from django.forms import ModelForm from .models import Blog class CreateBlogModelForm(ModelForm): class Meta: model = Blog fields = [‘title’, ‘description’] //exclude = [‘status’]
  • 44. Overriding Labels, HelpText, Widgets, HelpText etc in ModelForm support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Make following changes in the code: class CreateBlogModelForm(ModelForm): class Meta: …… labels = { ‘title’: ‘Blog Title’, ‘description’: ‘Blog Description’} widgets = { description: Textarea()}
  • 45. Adding Custom Validation in ModelForm support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Make following changes in CreatePostForm class: class CreateBlogModelForm(ModelForm): def clean_description(self): description = self.cleaned_data[‘description’] num_words = len(description.split(‘ ‘)) if num_words < 3: raise forms.ValidationError("Not enough words!") return description class Meta: …….. ● Note: Django automatically call any method starting with “clean_” during validation.
  • 46. Upload an Image support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Configure MEDIA_ROOT and MEDIA_URL in settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '/media/’) //Path where file stores MEDIA_URL = '/media/’ //Browser URL to access file ● Configure MEDIA_ROOT and MEDIA_URL in settings.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ …… ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • 47. Upload an Image Continued… support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Make following changes in forms.py class CreatePostForm(forms.Form): …… image = forms.FileField() ● Make following changes in views.py def create_post(request): form = CreatePostForm(request.POST, request.FILES) Blog(image = cleaned_data[‘image’]) ● Make following changes in HTML file <….. enctype="multipart/form-data">
  • 48. Development Process support@zekeLabs.com | www.zekeLabs.com | +91 8095465880
  • 49. Settings support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Django provides with a default settings file. ● We can create our own settings file as well. ● In case there are multiple settings file, we need to tell Django which file to use. For this we can use the environment variable DJANGO_SETTINGS_MODULE. export/set DJANGO_SETTINGS_MODULE=myproj.settings ● We can use settings variables in our code as well. For eg, from django.conf import settings if settings.DEBUG: ………..
  • 50. Exceptions support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Django raises some of its own exceptions as well as standard Python exceptions. ● Some Django exceptions are: ● ObjectDoesNotExist: raised when object not found for a query. ● FieldDoesNotExist: raised when a requested field doesn’t exist. ● MultipleObjectsReturned: raised when query returns multiple object but only one was expected. ● ViewDoesNotExist: raised when requested view doesn’t exist for a url. ● FieldError: raised when there is a problem with a model field. ● ValidationError: raised when data is not what was expected in the form. And many more…
  • 51. Django-admin and manage.py support@zekeLabs.com | www.zekeLabs.com | +91 8095465880 ● Both perform the same task except manage.py sets DJANGO_SETTINGS_MODULE environment variable to the project’s settings file. ● Syntax: django-admin <command> [options] manage.py <command> [options] ● For eg, django-admin makemigrations {app_name} django-admin migrate {app_name} django-admin runserver django-admin shell