Django 1.9 Help

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 14

Django 1.

9 Help (we make use of the project "djangoapp" in this doc to explain
the process)

#SECTION1 - DOWNLOADING, INSTALLING AND RUNNING YOUR DJANGO PROJECT.

Downloading Django on your computer: (This will install latest version of


django 1.9)

IF you are using python2.X.X (command):

pip install django


IF you are using python3.x.x (command):
pip3 install django

To downlaod a specific version of django you can use the follwoing command:

pip install django==x.y.z #x.y.z is the exact version u want to


install. [x.y.z == 1.9.2]

Concept of Project and App in Django :

Project: this is the complete project that you are creating using django framework.
A project can contain multiple Apps.

App: this represents a single module in your project. An app can exists in
multiple projects.

Creating your first django web Application

Use the command:


django-admin createproject <project_name> #
project_name can be name of the project you are working on

when you execute the above command a directory structure is


created as given below:

djangoapp
|
|- db.sqlite3
|- manage.py
|---- djangoapp
| (EXPLANATION OF
THESE FILES IN SECTION2 OF THIS DOC)
|- __pycache__
|- __init__.py
|- settings.py
|- urls.py
|- wsgi.py

All the files will be created autoimatically when you execute the
above command

From the command line go into the djangoapp directory and run the below
command to start your application

if you have installed python2.x.x


python manage.py runserver

if you have installed python3.x.x

python3 manage.py runserver

This will run your django application on localhost address :


127.0.0.1:8000

To run the app on your Computer IP address use the following command
inside the project folder:

python(3) manage.py runserver 192.168.1.10:8000


---> (3 is needed if you use python3)

Note: when you run the project for the first time you will get a warning as:

Warning: you have unapplied migrations

To overcome the above warning run the below command:

python(3) manage.py migrate


---> (3 if you use python3)
&
python(3) manage.py runserver

Point your browser to the address loacalhost:8000 this will initially


show content saying this is your first django page.

#END OF SECTION1

-----------------------------------------------------------------------------------
-----------------------------------
#SECTION2 - KNOWING THE DIFFERENT FILES IN DJANGO AND HOW TO USE THEM

IN SECTION1 when we use the command "python3 startproject djangoapp" it generated a


few files as shown in the file structure in section1

For Your reference here is the list of files that are generated

* settings.py
* urls.py
* manage.py
* admin.py (USER MUST CREATE THIS FILE)
* db.sqlite3
* views.py (USER MUST CREATE THIS FILE)
* forms.py (USER MUST CREATE THIS FILE)

settings.py -> this file contains all the required references to the
classes that django makes use. Additionally the file already contains some boiler
plate(GENERATED CODE) for your database, views , static files (CSS AND JS FILES)
configurations

NOTE: Depending on your need you can add other configurations to the file
which you want to make use in the project.

urls.py -> this file contains all the routes that your application requires.
Routes here mean its the URL PATH you normally traverse on your browser.

Ex:- url(r'^admin/', admin.site.urls) -> this URL in your


browser would be localhost:8000/admin

manage.py -> this file is one of the important file that we make use when we
run the project on localhost. do not edit this file as it can harm your project and
you might not be able to run your project.

admin.py -> this file should be created by the user. this is mainly used to
register a module of your project on the admin side. so that we can have access to
that module from the admin panel.

db.sqlite3 -> this file is part of the sqlite database that we make use of in
the project. Initially its empty. later this file is made use of by your project to
store all the tables and data you create in your project.

views.py -> this file contains all the function definitions that returns a
view (HTML PAGE) on your browser. The function call is made from the urls.py file
which has the actual path to which the user traverses to.

forms.py -> This file contains the code that is responsible for generating
forms (FOR EXAMPLE: USER REGISTRATION PAGE) on the browser. this uses the models.py
file.

models.py -> this file represnts the database of a module in which it resides
in.

IMPORTANT NOTE:
* ONLY A SINGLE COPY OF BOTH settings.py and db.sqlite3 is
present for th whole project.

* THE FILES admin.py,urls.py,views.py,forms.py,models.py is


present in every app (module) in the project.

Finally we also want to display HTML pages using django. To do that follow
these steps

* create a new folder by name templates in your project directory (in our
example its djangoapp directory)
* all the html files that you create can be stored in this directory.
* To make use of these HTML files in django you need to add an entry to the
TEMPLATES section in your settings.py. since TEMPLATES represents a dictionary you
must actually make an entry to the DIRS key. The entry is actually the absolute
path of your templates directory. In our djangoapp example it would look like:

'DIRS': ['/home/administrator/sampleApp/templates/',],

NOTE:
* since DIRS is list again you can add multiple templates path
which is made use by django to render the HTML page.
* every app you create can have its own templates directory and
its path should be added to the DIRS section.

we will make use of these things in the further sections.


#END OF SECTION2

#SECTION3 - CREATING A NEW MODULE (ALSO CALLED APP IN DJANGO) IN YOUR PROJECT

To crate a new app in your django project first you need to be in your project
folder in terminal. You can verify by running the pwd (present working directory)
command.

the output should be similar to "/home/administrator/sampleApp".

Next step is to run the below command:

django-admin startapp <appname> --> appname can


be the module name you want to create in your project.

this will create a folder with the appname you provide and
generates a few files in the folder. the structure is as follows:

<appname>FOLDER
|
|- __pycache__
|- migrations FOLDER
| |
| |- __pycahce__
| |- __init__.py
|
|- __init__.py
|- admin.py
|- apps.py
|- models.py
|- tests.py
|- urls.py (USER MUST CREATE THIS FILE)
|- views.py

NOTE: these are the files that gets created whenever your
create a new app for your project except for urls.py

In the the project "djangoapp" we have created a new app by


name studentapp

#END OF SECTION3

#SECTION4 - MAKING USE OF THE NEWLY CREATED APP IN YOUR PROJECT

STEP1 create an app and register


-----

To make use of the newly created app in your project you have to register your app
in the project. This can be done by adding an entry to the INSTALLED_APPS section
in the settings.py file of your project.
Intially the INSTALLED_APPS section would be a python list of APPS present in your
project by default and will look as shown below:

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

Now we make use of the studentapp we just created in the previous


section and add it to the list as shown below:

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

NOTE:
* since the INSTALLED_APPS section is a pythion list you need add
comma (,) at the end and its compulsory.
* Any new app that you create in django project must first be
registered here in this list.

STEP2 To create an HTML page and render it on the browser


-----

In our example we are trying to render a HTML page that displays the list of all
students. To do that follow these below steps

-> In section2 we learned how to create a templates directory and store all
your html files.
-> create a new html file under that folder. give the file the name of your
choice. (In our example its list.html)
NOTE: Always try to use proper naming conventions for naming html files
as it will be easier to use without any confusion
-> write some html code in the file you created and keep it ready.

Till now we just created the file and kept it ready for use.

STEPS FOR ACTUALLY RENDERING THE HTML page on browser.

-> firstly we need to open the urls.py file in the studentapp. if you observe
its empty now we add some code (i.e urlpatterns or routes) like this:
from django.conf.urls import url
from studentapp.views import listall

urlpatterns = [
url(r'^all/',listall),
]

Note: observe carefully that we have imported a function called "listall"


from our studentapp views file which we will actually define now.
This needs to be repeated for the functions you want to make use in the
urls.py file.

Open your views.py file under studentapp

you will have a single line of code in views.py file as shown below:

from django.shortcuts import render

you need to change this line as follows:

from django.shortcuts inport


render_to_response

render_to_response is a function we make use constantly to render


html pages in django.

remember we have imported a function called listall in the urls.py file. now
lets define the same function here as follows:

def listall(request):
--> request is a implicit object we pass to all the functions in views.
return render_to_response('list.html')
--> list.html is the file you create in the templates directory.

now before we actually run the project. there is one more concept on urls.py
that we will look at now

The concept is that every app in django and the project itself has a seperate
urls.py file. The urls.py file of the project is like the root urls for your
project and the urls.py file that is present in the app are the sub urls specific
to your app. lets take the djangoapp example. in this the djangoapp contains a
urls.py file which is like the root urls file. thers is one more urls.py file that
is present in the studentapp module that we created which only has the urls of that
module.

urls.py of studentapp module:

from django.conf.urls import url


from studentapp.views import
listall
urlpatterns = [
url(r'^all/',listall),
]

As you can see there is only one route call all. this actually
calls the listall function in the views.py file

Now lets look at urls.py file of the djangoapp project:

from django.conf.urls import


url,include
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),

url(r'^student/',include('studentapp.urls')),
]

if you observe carefully here we see that we have used the include
function to include all the urls of the studentapp into the project whenever the
request points to localhost:8000/student on the browser.

since the urls.py file in studentapp contains a route called all and if
the user points the browser to the url localhost:8000/student/all/ it would render
the HTML page list.html

In this way for every app you create you can include them using the
include function on the main urls.py file.

finally its time to run your project using the command as previously shown and
point your browser url to localhost:8000/student/all/

NOTE: make sure to have some dummy content on the HTML so that you can be sure that
you have rendered that page on the browser.

Before ending the section. lets look at a simple concept of navigation in django.

for the navigation we make use of the these files in django

* urls.py
* views.py
* the HTML page where you want the links to be present.
* the HTML page you would want to traverse to.

--> the first step is to create a new HTML page that you would like to
traverse to. in our djangoapp example we create a about.html page in templates
directory and see how to traverse from the list.html page that we already created.
--> second we add a entry to the urls.py (the route) where you want the page
to be rendered. In our example we add this below lines to the urls.py file in
studentapp

url(r'^about/',about), --> added to the


url patterns list

from studentapp.views import


listall,about --> about function imported from the views file.

--> thirdly we define the function about which actually renders the page

def about(request):
return
render_to_response('about.html')

--> Next we will add a anchor tag in the list.html page. the href property of
the anchor tag will be pointed to the about page as shown below.

<a href="/student/about/">ABOUT</a>

--> finally you run the project and go to the list page. you should see a
link by name ABOUT and when you click it you will be taken to the about page.

In our example we also have link in the about page to traverse back to the
list page.

NOTE: Any simple page to page navigation involves the same process.

#END OF SECTION4

#SECTION5 - PASSING DATA TO YOUR VIEWS AND BASIC FORM HANDLING.

PASSING DATA TO YOUR VIEWS

As you know in the MVC archtecture templates are dummy (dumb). they
just display data (content) and they dont to any kind of data processing. In this
section we learn how to pass data to your views and how to render it in the HMTL
page.

There are two steps to this process.

1. we have to pass data to view (i.e. HTML PAGE) in the views.py file.

2. using the django template language to render the data that is passed
to the HTML page.

step1 --> pass data to view

def listall(request):

name_list=["Alice","Bob","John","Justin","Mark"]
return
render_to_response('list.html',{'first_name':name_list})

from the code observe carefully, firstly we create a python


list of names using the variable name_list.
next in the retrun statement we assign the list to the
variable called first_name. if you observe the syntax its a python dictionary
having key value pairs. Here first_name is a key which represents a list as its
assigned to a list (name_list)

IMPORTANT: name_list is a local variable you use to create


the list and actually since we are assigning it to first_name variable, i.e.
first_name is the variable passed to the page list.html

NOTE: since its a python dictionary, you can pass multiple


key value pairs at the same time.

step2 --> displaying the data on the template (list.html) using


django template language

NOTE ON TEMPLATE LANGUAGE SYNTAX:

{{ varname }} --> two curly braces are used


in the template to directly display the value of the variable.

{% directives %} --> this syntax is made use


for programming directives like if conditon. for loops and also other directives
specific to template language like "extends" for template inheritance.

In step1 we passed a variable to the list.html page


called first_name. now lets make use of this variable in the HTML page to display
the values stored in the variable.

REMEMBER first_name is a list and hence we use for


loop to iterate over the list to display individual values. we make use of the
following code to display the values in the list.

<ul>
{% for name in
first_name%}
<li>{{ name }}</li>
{% endfor %}
</ul>

here we are iterating over the list first_name one by


one and displaying them.

EXCERCISE : You can also try to pass multiple


variables to the page and display them

BASIC FORM HANDLING

In this section we will see how to fill the form and submit and display
the values submitted.

Firstly we will add entries to the urls.py file:

url(r'^addinfo/',studinfo),
--> this route is is where the form is displayed for submission.
url(r'^dispinfo/',dispinfo),
--> this route will actually display the values submitted in the form.

Second we define the functions studinfo, dispinfo in the views.py file


as follows:

def studinfo(request):
return
render_to_response('studinfo.html',context_instance=RequestContext(request))

def dispinfo(request):
try:
if request.POST:
name = request.POST.get('sname')
qual = request.POST.get('qual')
return
render_to_response('info.html',
{'name':name,'qual':qual},context_instance=RequestContext(request))
except:
pass
return
render_to_response('info.html',context_instance=RequestContext(request))

IMPORTANT: make sure to have csrf classes in the middleware


classes in settings.py. by default it will be there. if not add the below line as
entry in the middlewareclasses section.

django.middleware.csrf.CsrfViewMiddleware

NOTE: in our example djangoapp we make use of the POST request.


its better than get request security wise. The reason for using POST method is that
it sents the form details along with the headers and it does not show up in the
url.

we also make use of the directive in your template {% csrf_token


%} where your form exists. csrf stands for cross site request forgery. This is a
security mechanism against invalid form requests. we also make use of the function
RequestContext in the views.py file. the purpose of using RequestContext is to
process the csrf_token that is present with the form.

Finally we need two templates that we need to create, in our


example app we have created studinfo.html that contains the form, info.html which
actually displays the submitted values. The template code is the template files in
our example app.

RUN the project to see it in action

DO IT ON YOUR OWN EXCERCISE : create few more fields on your own


and try submitting and displaying.
Also try using GET
method instead of POST.
#END OF SECTION5

#SECTION6 - CREATING DATABASES USING MODELS.PY AND FORM HANDLING USING DATABASES
AND HANDLING STATIC FILES

To create databases in django we make use of the models.py file. in this file we
define tables as classes where class name represents table name and attributes
represent columns in the table. In our example djangoapp project we have created a
model for the studentapp module.

First we need to write a class in the models.py file that repesents the table as
follows:

class StudentInfo(models.Model):
--> table StudentInfo
gender = (('M','Male'),('F','Female'),)
--> value options for gender field
first_name = models.CharField(max_length=30)
--> first name as a charecter field
last_name = models.CharField(max_length=15)
--> last name as a charecter field
qualification = models.CharField(max_length=10)
--> qualification as a charecter field
age = models.IntegerField()
--> age as Integer field
gender =
models.CharField(max_length=1,choices=gender) --> gender as a choice field

def __str__(self):
return self.first_name -->function inside
the class is written to display the object name

models.Model is a inbuilt object that is passed to every class that you


write in this file to make use of it for different type of fields for the data.

NOTE: you can write multiple classes in the same file that represents
multiple tables for that module.

Second step is to run the migrations and apply them

IMPORTANT NOTE:
* make sure you finalize the table schema before even you apply migrations. or
else you may have to rollback all the changes you have made.

* Also make sure you have registered your module in the INSTALLED_APPS section in
settings.py file.

To run migrations run the following command:

python(3) manage.py makemigrations --> 3


if only using python3

To apply the migrations run the following command:(THIS ACTUALLY CREATES THE
TABLE IN YOUR DB)

python(3) manage.py migrate --> 3


if only using python3

OPTIONAL STEP : you can also register your model in the admin.py file if you want
the admin to modify the records for that table. To do this add the following code
in admin.py

from studentapp.models import StudentInfo -->


import staement

admin.site.register(StudentInfo) -->
register StudentInfo table on admin side

Run your project and login to admin site and check the newly created
table.

This optional step is really helpfull if you want to add some dummy date into
the table easily for testing purposes.

Displaying records in the DB on the tmplate.

To do this there is two very simple steps:

1. add a route entry in urls.py file where you want to display the records
from DB.

url(r'^viewall/',all), --> viewall


is the route, all is the function call.

2. define the function in views.py file which actually returns the data from
the DB and use the template language to format the output on the HTML page.

from studentapp.models import StudentInfo --> import


the StudentInfo model from the models file

define all(request):
return render_to_response('all.html',
{'StudList':StudentInfo.objects.all()})

In the all.html write this code to display the data passed:

{% for student in StudList %}

{{ student.first_name }}
{{ student.last_name }}
{{ student.qualification }}
{{ student.age }}
{{ student.gender }}

{% endfor %}

Run the project and see it in action. Do remember to have some dummy
data before you want to display the data from the DB.

FORM HANDLING USING DATABASES

To create forms we make use of the forms.py file. This file is not created
when you create the app. you need to create it. forms are also written as classes
in django. the class name represents the form name and the attributes represents
the fields in a form. The best part of form in django is using the database as a
source to create it.

write the following code in your forms.py (in our example we crate the
forms.py file in the studentapp module)

from studentapp.models import StudentInfo


--> importing your model StudentInfo

class StudentForm(forms.ModelForm):
--> StudentForm is the form name
gender = (('M','Male'),('F','Female'),)
--> choices for your gender field
first_name = forms.CharField(label='First
Name') --> first name field
last_name = forms.CharField(label='Last Name')
--> last ane field
qualification =
forms.CharField(label='Qualification') -> qualification field
age = forms.IntegerField(label='Age')
--> age field
gender =
forms.ChoiceField(label='Gender',choices=gender) --> gender selection field

class Meta:
--> this actually refers to the source which your forms use to generate
model = StudentInfo
the fields and save form data.
fields = '__all__'
--> fields option is used to

add a route to your urls.py in studentapp module where you want to display
the form as follows:

from studentapp.views import


listall,about,studinfo,dispinfo,studadd

url(r'^new/',studadd),

now define the studadd function in the views.py file in studentapp module
that you are using the urls.py file

from studentapp.forms import StudentForm


--> import studentform from forms file
from django.http import HttpResponseRedirect
--> import http redirect from http package
from django.template.context_processors import csrf
--> csrf import

def studadd(request):
if request.POST:
--> if the request is post request
form = StudentForm(request.POST) -->
create a new student form passing the request info
if form.is_valid(): -->
validate the form filled by the user
form.save() -->
if valid save it to DB or else show invalid message
return
HttpResponseRedirect('/student/new/') --> redirect to that route
else:
form = StudentForm() --> if
its not post request create a empty form
args = {} -->
create a args dictionary
args.update(csrf(request)) -->
generate a csrf token and store it in args
args['form'] = form --> store
the generated form in the form key of args
return
render_to_response('add.html',args,context_instance=RequestContext(request))

--> return the view and pass the data to the view.

In the template add.html write the following code which renders your form on
the page

<form action="/student/new/" method="post">{%


csrf_token %}
{{form.as_p}}
<input type="submit" value="add Student">

EXCERCISE : closely observe that we are setting the form action attribute to
the route that we added in the urls.py. try to analyze why we are doing thet.

now run your project to see it in action.

TRY TO CREATE FEW MORE FORMS FOR YOURSELF TO MAKE SURE YOU ARE CONFIDENT WITH
THE CONCEPT

HANDLING STATIC FILES

#END OF SECTION6

You might also like