Professional Documents
Culture Documents
Django 1.9 Help
Django 1.9 Help
Django 1.9 Help
9 Help (we make use of the project "djangoapp" in this doc to explain
the process)
To downlaod a specific version of django you can use the follwoing command:
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.
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
To run the app on your Computer IP address use the following command
inside the project folder:
Note: when you run the project for the first time you will get a warning as:
#END OF SECTION1
-----------------------------------------------------------------------------------
-----------------------------------
#SECTION2 - KNOWING THE DIFFERENT FILES IN DJANGO AND HOW TO USE THEM
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.
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.
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.
#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.
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
#END OF SECTION3
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',
]
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.
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.
-> 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),
]
you will have a single line of code in views.py file as shown below:
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.
As you can see there is only one route call all. this actually
calls the listall function in the views.py file
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.
* 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
--> 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
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.
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.
def listall(request):
name_list=["Alice","Bob","John","Justin","Mark"]
return
render_to_response('list.html',{'first_name':name_list})
<ul>
{% for name in
first_name%}
<li>{{ name }}</li>
{% endfor %}
</ul>
In this section we will see how to fill the form and submit and display
the values submitted.
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.
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))
django.middleware.csrf.CsrfViewMiddleware
#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
NOTE: you can write multiple classes in the same file that represents
multiple tables for that module.
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 apply the migrations run the following command:(THIS ACTUALLY CREATES THE
TABLE IN YOUR DB)
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
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.
1. add a route entry in urls.py file where you want to display the records
from DB.
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.
define all(request):
return render_to_response('all.html',
{'StudList':StudentInfo.objects.all()})
{{ 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.
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)
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:
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
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
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.
TRY TO CREATE FEW MORE FORMS FOR YOURSELF TO MAKE SURE YOU ARE CONFIDENT WITH
THE CONCEPT
#END OF SECTION6