Django chapter 2

A Bookmark Application in Django

In django I have learned about some basic concepts about files they are : -

urls & views : It is used to create a mainpage

Models : For designing a initial database schema it is used.

Template : To create the main page of application it is used.

==>> Finally we generate userpages to put altogether .

Some simple steps before creating an application : -

(1) To create a application we have to create an entry point to it . This we can do in the form of urls .

(2) By creating a url we can call a python function to be displayed on a webpage .

CREATING THE MAIN PAGE VIEW

(3)Here a view is a python function to generate the corresponding page by a request.

Application is a container of views & models.

To create an apps move to bestsites_bookmarks folder and give the code :-

$python manage.py startapp bestsites

where bestsites is the application name.

By giving this command it creates a folder bestsites with 3 files in it .

_init_.py    --->  It shows bestsites as a python package.
views.py   --->  It contains views
models.py --->  It contain data models .

To Create a Main Page View

open the bestsites/views.py file and enter the code : -

# Create your views here. from django.http import HttpResponse
def main_page(request):
 output = '''
  <html>
   <head><title>%s</title></head>
   <body>
    <h1>%s</h1><p>%s</p>
   </body>
  </html>
 ''' % (
    'bestsites bookmarks',
    'This is a newsite for bestsites bookmarks',
     'Where the bestsites can be stored and shared'
 )
 return HttpResponse(output)
Code Explanation:
(1) First we import a class Http Response from a module django.http  .
This class is needed for the response page
(2) Then we define a function with a parameter request . 
Which gets the user input & other information like the request.GET, request.POST, & request.COOKIES
(3) Next we give the HTML code wrap with HTTPResponse object & return it.
To Create the Main Page url : -
As said before the view is a function that gets user input & returns page as output .
For this we have to connect to main url . urls.py file code should be edited like this
 
from django.conf.urls.defaults import *

from bestsites.views import *
# Uncomment the next two lines to enable the admin:
# admin.autodiscover()

urlpatterns = patterns('',
    (r'^$', main_page),
    # Examples:
    # url(r'^$', 'bestsites_bookmarks.views.home', name='home'),
    # url(r'^bestsites_bookmarks/', include('bestsites_bookmarks.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    #url(r'^admin/', include(admin.site.urls)),
)
Code Explanation :
(1) Here we import django.conf.urls for to mention necessary funtions to define url.
(2)Then we import from bestsites.views to access our views to connect URLs
(3)Then the pattern function is been used to define URL table
^ and $.r'' are used as python raw strings
here 
^ -> beginning of string
$ -> end of the string 
^$ -> it doesnt contain anything its an empty string.
Thus in view of main page the root url should be empty.
The regular expression is given in detail at http://docs.python.org/library/re.html
Some regular expression descriptions : -
.(Dot)              -->      Any Character
^(Caret)            -->      Start of String
$                   -->      End of the String
*                   -->      0 or more repitations
 
+                   -->      1 or more repitations
?                   -->      0 or 1 repitations
|                   -->      A|B  means A or B
[a-z]               -->      Any lowercase character
\w                  -->      Any Alphanumeric character or _
\d                  -->     Any digit
Now we can run the server at 
http://127.0.0.1.:8000/
IF you get any typeError like that :
You can see the error have been created by clicking the Switch to copy-and-paste view   
link there
 
And can find the error under the heading traceback:


 
 And if this program is excecuted it returns an output like this 

 
Models : Designing an Initial Database  

  The django database is different , it obtains access from python classes . 

For this bestsites application we are going to create the following at our database :

Users(ID, username, password, email)

Links(ID, url)

Bestsites(ID, title, userid_id, link_id)

Datamodel for links table : -
Now open bestsites/models.py and add the following code
from django.db import models
class Link(models.Model):
 url = models.URLField(unique=True)

Code Explanation :

models --> package contains classes to define models

link   --> class
             |
             v
           inherits from (models.Model)
                            |
                            v
                          base class

The link --> contain 1 field name url

url type is models.URLField

This field should be unique

Django provides a number of field types some of them  are : -

IntegerField       -->     An integer

TextField          -->    An large text field

DateTimeField      -->    date and time field

EmailField         -->    email field with 75 character max

URLField           -->    URL Field with 200 charcter max

FileField          -->    A file - upload field


To use this model we have to activate it in our Django project have been created. 

==> Now edit settings.py file . And add application name to installed apps variable.

INSTALLED_APPS = (
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'bestsites_bookmarks.bestsites' 
)

Now to create a table for the link data model use the command .

$python manage.py syncdb

This command is used whenever we add a datamodel to create its table in database

To examine the sql query , use this command

$python manage.py sql bestsites
 
The output of this command will look like : -
BEGIN;
CREATE TABLE "bestsites_link" (
   "id" integer NOT NULL PRIMARY KEY,
   "url" varchar(200) NOT NULL UNIQUE
)
;
COMMIT;
 
==> You can notice that ID field have been created automatically.
==> The ID acts as an PRIMARY KEY for the table.
To create entries in table use the command
python manage.py shell
This shell differs from standard python shell by 2 ways they are : - 
(1) The project path is added to sys.path
(2) An environment variable is created to hold path to our settings.py
To import contents of module
>> from bestsites.models import *
To add a new link --> create a instance of link class & save it .
 
>>link1 = Link(url='http://www.manualian.blogspot.com')
 
 To save the link use 
 
>>> link1.save()


To change the link url use :

>>> link2.url = 'http://wwww.google.com'

here everytime we should give the link.save() to save the contents entered

To get the list of all link objects use : -

>>> links = Link.objects.all()

>>> for link in links :
...  print link.url
... 
http://www.manualian.blogspot.com
http://wwww.google.com

To get the object by id 
>>> Link.objects.get(id=1)
<Link: Link object>
To delete a link use :

>>> link2.delete()
To get the object count use:

>>> Link.objects.count()
1
 
The User Data Model 
It is easy to create a user data model in Django because django provides a user accounts like username
 
password,email and so on.
     The model is called as user and it is located at django.contrib.auth.models package
To use this model use the command .
>>> from django.contrib.auth.models import User
To get user objects use the dir function.
 
dir(User)
We can directly use the user datamodel without any codes.
The Bestsites DataModel
This model links the user and the link data model. For this insert the code at bestsites/models.py 
 
from django.contrib.auth.models import User 
class Bestsites(models.Model):
 title = models.CharField(max_length=200)
 user = models.ForeignKey(User) 
 link = models.ForeignKey(Link)
First we import the model called User . Then we define a class called Bestsites. This model contains a text
field called title and 2 foreign keys user and link to populate content from those tables.
 
Then run
 $python manage.py syncdb
 
Now to see the table generated use 

$python manage.py sql bestsites

BEGIN;
CREATE TABLE "bestsites_link" (
    "id" integer NOT NULL PRIMARY KEY,
    "url" varchar(200) NOT NULL UNIQUE
)
;
CREATE TABLE "bestsites_bestsites" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(200) NOT NULL,
    "user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
    "link_id" integer NOT NULL REFERENCES "bestsites_link" ("id")
)
;
COMMIT;

Creating a Template for Main Page
 
For template Django provides a component called template System which will help to 
seperate Django Views from HTML code.
 For this create a seperate template folder in projects folder. Then to link template folder 
with Django, open settings.py and in TEMPLATE_DIRS Variable add the absolute path or use the 
following code

import os.path
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(_file_), 'templates'),
)
Then create a file called main_page.html in template folder . And insert the code : -

<html>
 <head>
  <title>{{ head_title }}</title>
 </head>
 <body>
  <h1>{{ page_title }}</h1>
  <p>{{ page_body }}</p>
 </body>
</html>
The template structure is normal HTML with only one difference the {{}} (double braces) which enable us
us to change the code (i.e,) the template variables are surrounded with double braces
To use this template in view edit bestsites/views.py and write the code : -

from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
def main_page(request):
 template = get_template('main_page.html')
 variables = Context({
  'head_title': 'Bestsites Bookmarks'
  'page_title': 'Welcome to New Django Bestsites'
  'page_body': 'Where you can store and share bookmarks!'
 })
 output = template.render(variables)
 return HttpResponse(output)
 
Code Explanation  
Here we use get_template method from django.template method from django.template.loader
module . This is used to take filename & return a template object . To set variable with 
values we create a object called variables of type context .
 
To replace template variables & create a HTML output we use render method . This takes 
context object as a parameter and pass variable objects to it . 
 
Then return the HTML output with HTTPResponse object .
 
Put altogether : Creating User Pages
 
Creating the URL : open urls.py and edit it .
 
urlpatterns = patterns('',
    (r'^$', main_page),
    (r'^user/(\w+)/$', user_page),

)
 
Here \w --> means a alpahnumeric character or a underscore .
     + --> to match one or more repitations
     \w+ --> consists of alphanumeric & underscore .

Writing the View

Thus we have created a new url to the url table . Now we should wrire a view for it.
Open bestsites/view.py and then add the code.
 
from django.http import HttpResponse, Http404 
from django.contrib.auth.models import User
def user_page(request, username):
 try:
  user = User.objects.get(username=username)
 except:
  raise Http404('Requested user has not found')
 bookmarks = user.bookmark_set.all()
 template = get_template('user_page.html')
 variables = Context({
  'username' : username,
  'bookmarks' : bookmarks
 })
 output = template.render(variables)
 return HttpResponse(output)
 
Code Explanation :
Like our normal view this function also takes request as a parameter with another parameter
username . The Url pattern has a parenthesis, the string captured is passed as a parameter to 
username .
User.objects.get is used to get the username requested.
If the username is not found a 404 error is passed.
To get the list of all bestsites_set.all() is been used.
Designing the template :
To design a template enter the code at file user_page.html
<html>
 <head>
  <title> Bestsites Bookmarks - User: {{ username }}</title>
 </head>
 <body>
  <h1>Bestsites for {{ username }}</h1>
  {%s if bestsites %s}
   <u1>
    {% for bestsites in bestsites %}
     <li><a href="{{ bestsites.link.url }}">
      {{ bestsites.title }}</a></li>
    {% endfor %}
   </u1>
  {% else %} 
   <p> No bestsites found </p>
  {% endif %}
 </body>
</html>
Here we use the if condition for condition to display bestsites . Then if condition here is used to ensure that the 
the bookmarks variable is not empty.
To check whether a variable is empty or not we can use this code.

{% if variable %}
 <p> Variable contains data </p>
{%else%}
 <p> variable is empty </p>
{%end if%}
To iterate through a list & print the items use the code .
{% for item in list  %}
 {{item}}
{% endfor %}
If a variable has attribute we can use
{{ variable.attribute }}
 
Now we can launch the development server at http://127.0.0.1:8000/user/your_username 

Django chapter 1

Hi friends,
          Today I have started learning django from basics . I want to create a simple bookmarking site in django with project name bestsites_bookmarks . I have given the steps to be followed in django.

To create a project use :

$django-admin.py startproject bestsites_bookmarks



This command creates 4 files

They are : -  _init_.py , manage.py , settings.py and urls.py

To Create a Database for  bestsites_bookmarks :

Now open settings.py in editor . It will have django settings for bestsites_bookmarks
 
DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Now we have to assign the database engine to sqlite3 which might be preinstalled along with python 2.7  . And we assign the database to be used in engine and a descriptive name for database name i.e, bookmarksdb

'ENGINE': 'sqlite3',
'NAME': 'bookmarksdb',

Now to populate the database with tables  , move to project folder and enter the command

$python manage.py syncdb

This will ask for the superuser to be created give yes and the username and password to be used.

Launching the Development Server

Now we can start the server using the command

$python manage.py runserver

now open the browser and type

http://localhost:8000/

It will show a screen like this : -

This url shows that it runs on port number 8000

To change the port number use the command

python manage.py runserver 5000 - > you can give a port number u like here.