Saturday, July 3, 2010

Design your URLs in Django


The first step of writing views is to design your URL structure. You do this by creating a Python module, called a URLconf. URLconfs are how Django associates a given URL with given Python code.
When a user requests a Django-powered page, the system looks at the ROOT_URLCONF setting, which contains a string in Python dotted syntax. Django loads that module and looks for a module-level variable called urlpatterns, which is a sequence of tuples in the following format:(regular expression, Python callback function [, optional dictionary])
When you ran django-admin.py startproject mysite at the beginning of
it created a default URLconf in mysite/urls.py. It alsoautomatically set your ROOT_URLCONF
setting (in settings.py) to point at that file:

ROOT_URLCONF = 'mysite.urls'
Time for an example. Edit mysite/urls.py so it looks like this: 
from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^polls/$', 'mysite.polls.views.index'),
    (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'),
    (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'),
    (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
    (r'^admin/', include(admin.site.urls)),
)
Write your first view

Well, we haven't created any views yet -- we just have the URLconf. But let's make sure Django is following the URLconf properly.Fire up the Django development Web server:
python manage.py runserver
Now go to "http://localhost:8000/polls/" on your domain in your Web browser. You should get a pleasantly-colored error 
page with the following message:
ViewDoesNotExist at /polls/

Tried index in module mysite.polls.views. Error was: 'module' object has no attribute 'index'
This error happened because you haven't written a function index() in the module mysite/polls/views.py.
Write the first view. Open the file mysite/polls/views.py and put the following Python code in it:
from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")
This is the simplest view possible. Go to "/polls/" in your browser, and you should see your text. Now lets add a few more views. These views are slightly different, because they take an argument (which, remember, is passed in from whatever was captured by the regular expression in the URLconf): 
def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)

def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request, poll_id):
    return HttpResponse("You're voting on poll %s." % poll_id)

Write views that actually do something
Eachview is responsible for doing one of two things: Returning an HttpResponseobject containing thecontent for the requested page, or raising an exception such as Http404. The rest is up to you.\Your view can read records from a database, or not. It can use a template system  such as Django's -- or  a third-party Python template system -- or not. It can generate a PDF file, output XML, create a ZIP file  on the fly,  anything you want,  using whatever Python libraries you want.All Django wants is that HttpResponse. Or an exception.Because it's convenient, let's use Django's own database API,  which we covered in. Here's one stab at the index() view, which displays the latest 5 poll questions in the system, separated by commas,  according to publication date:
from django.template import Context, loader
from mysite.polls.models import Poll
from django.http import HttpResponse

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    t = loader.get_template('polls/index.html')
    c = Context({
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(t.render(c))
That code loads the template called "polls/index.html" and passes it a context.
The context is a dictionary mapping template variable names to Python  objects.
Reload the page. Now you'll see an error:

TemplateDoesNotExist at /polls/
polls/index.html
There's no template yet. First, create a directory, somewhere on your filesystem, whose contents
Django can access. (Django runs as whatever user your server runs.) Don't put them under your 
document root, though. You probably shouldn't make them public, just for security's sake. Then edit TEMPLATE_DIRS
 in your settings.py to tell Django where it can find templates -- just  as you did in the "Customize the admin look and 
feel" .
 When you've done that, create a directory polls in your template directory. Within that, create a file called index.html. 
Note that our loader.get_template('polls/index.html') code from above maps to "[template_directory]/polls/index.html"
 on the filesystem. Put the following code in that template: 

{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

A shortcut:render_to_response()
It's a very common idiom to load a template, fill a context and return an HttpResponse object with the result of the rendered template. Django provides a shortcut. Here's the full index() view, rewritten:
from django.shortcuts import render_to_response
from mysite.polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Note that once we've done this in all these views, we no longer need to import
loader, Context and HttpResponse.

The render_to_response() function takes a template name as its first argument and a dictionary as its optional second 
argument. 
It returns an HttpResponse object of the given template rendered with the given context.

A shortcut: get_object_or_404()
It's a very common idiom to use get()  and raise Http404  if the object doesn't exist. Django provides a
 shortcut. Here's the detail()  view, rewritten:
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})

Use the template system
Back to the detail()  view for our poll application. Given the context  variable poll,  here's what the "polls/detail.html"
 template might look like:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice }}</li>
{% endfor %}
</ul>

The template system uses dot-lookup syntax to access variable attributes. In the example of {{ poll.question }}, first 
Django does a dictionary lookup on the object poll. Failing that, it tries attribute lookup -- which works, in this case.  
If attribute lookup had failed, it would've tried calling the method question() on the poll object. 
Method-calling happens in the {% for %} loop: poll.choice_set.all is interpreted as the Python code poll.
choice_set.all(), which returns an iterable of Choice objects and is suitable for use in the {% for %} tag. 
Simplifying the URLconfs
Take some time to play around with the views and template system. As you edit the URLconf, you may notice there's a fair 
bit of redundancy in it:

 urlpatterns = patterns('',
    (r'^polls/$', 'mysite.polls.views.index'),
    (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'),
    (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'),
    (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
)

Namely, mysite.polls.views is in every callback. Because this is a common case, the URLconf framework provides a 
shortcut for common prefixes. You can factor out the common prefixes and add them as the first argument to patterns(),
 like so: 
urlpatterns = patterns('mysite.polls.views',
    (r'^polls/$', 'index'),
    (r'^polls/(?P<poll_id>\d+)/$', 'detail'),
    (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
    (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
)
This is functionally identical to the previous formatting. It's just a bit tidier.

Decoupling the URLconfs
While we're at it, we should take the time to decouple our poll-app URLs from our Django project configuration. Django apps are meant to be pluggable -- that is, each particular app should be at this point, thanks to the strict directory structure that python manage.py startapp created,  but one part of it is transferable to another Django installation with minimal fuss. Our poll app is pretty decoupled coupled to the Django settings: The URLconf. We've been editing the URLs in mysite/urls.py,but the URL design of an app is specific to the  app, not to the Django installation -- so let's move the URLs within the app directory. Copy the file mysite/urls.py to mysite/polls/urls.py. Then, change mysite/urls.py to remove the poll-specific URLs and insert an include():

# ...
urlpatterns = patterns('',
    (r'^polls/', include('mysite.polls.urls')),
    # ...
include(), simply, references another URLconf. Note that the regular expression doesn't have a $ (end-of-string match 
character) but has the trailing slash. Whenever Django encounters include(),  it chops off whatever part of the URL 
matched up to that point and sends the remaining string to the included URLconf for further processing. 
Here's what happens if a user goes to "/polls/4/" in this system: 
  • Django will find the match at '^polls/' 
  • Then, Django will strip off the matching text ("polls/") and send the remaining text -- "34/"  -- to 
    the 'mysite.polls.urls' URLconf for further processing. 
Now that we've decoupled that, we need to decouple the 'mysite.polls.urls' URLconf by removing the leading "polls/", 
 from each line, and removing the lines registering the admin site:  
urlpatterns = patterns('mysite.polls.views',
    (r'^$', 'index'),
    (r'^(?P<poll_id>\d+)/$', 'detail'),
    (r'^(?P<poll_id>\d+)/results/$', 'results'),
    (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
The idea behind include() and URLconf decoupling is to make it easy to plug-and-play URLs. 
Now that polls are in their own URLconf, they can be placed under "/polls/", or under "/content/polls/", or any other URL root, and the app will still work. All the poll app cares about is its relative URLs, not its absolute URLs. Credit : https://docs.djangoproject.com

Friday, July 2, 2010

Testing and Consultancy Cell ( TCC ) of G.N.D.E. College Ludhiana.

Consultancy Services are being rendered by various Departments of the College to the industry, Sate Government Departments and Entrepreneurs and are extended in the form of expert advice in design, testing of materials & equipment, technical surveys, technical audit, caliberation of instruments, prepartion of technical feasibility reports etc.
This consultancy cell of the college has given a new dimension to the development programmes of the College. Consultancy projects of over Rs. one crore are completed by the Consultancy cell during financial year 2009-10.

Web-page  :- TCC GNDEC Ludhiana.
Email : - tcc@gndec.ac.in

Thursday, July 1, 2010

" diff " and " tasksel " command in Linux

TASKSEL

NAME
       tasksel - a user interface for installing tasks
SYNOPSIS
       tasksel install <task>


       tasksel remove <task>



       tasksel [options]



DESCRIPTION


       tasksel shows all available tasks and allows to user to select ones to install
example : tasksel







OPTIONS

       -t, --test
           test mode; don't actually install or remove packeges



       --new-install

           automatically select some tasks without even displaying them to the user; default other tasks to on; used during new Debian installs.



       --list-tasks

           list on stdout the tasks that would be displayed in the tasksel interface



       --task-packages task

           lists on stdout the packages that are available and part of the given task



           Note that this option may be given more than once.




       --task-desc task

           outputs the extended description of the given task



       --debconf-apt-from waypoint

           Start the debconf-apt-progress bar here.



       --debconf-apt-to waypoint

           End the debconf-apt-progress bar here.



       --debconf-apt-progress options

           Pass the specified options to the debconf-apt-progress command that tasksel runs. These will be appended to any --from and --to options constructed by tasksel
           itself based on --debconf-apt-from and --debconf-apt-to options.




DIFF
Usage: diff [OPTION]... FILES
Compare files line by line.

  -i  --ignore-case  Ignore case differences in file contents.
  --ignore-file-name-case  Ignore case when comparing file names.
  --no-ignore-file-name-case  Consider case when comparing file names.
  -E  --ignore-tab-expansion  Ignore changes due to tab expansion.
  -b  --ignore-space-change  Ignore changes in the amount of white space.
  -w  --ignore-all-space  Ignore all white space.
  -B  --ignore-blank-lines  Ignore changes whose lines are all blank.
  -I RE  --ignore-matching-lines=RE  Ignore changes whose lines all match RE.
  --strip-trailing-cr  Strip trailing carriage return on input.
  -a  --text  Treat all files as text.

  -c  -C NUM  --context[=NUM]  Output NUM (default 3) lines of copied context.
  -u  -U NUM  --unified[=NUM]  Output NUM (default 3) lines of unified context.
    --label LABEL  Use LABEL instead of file name.
    -p  --show-c-function  Show which C function each change is in.
    -F RE  --show-function-line=RE  Show the most recent line matching RE.
  -q  --brief  Output only whether files differ.
  -e  --ed  Output an ed script.
  --normal  Output a normal diff.
  -n  --rcs  Output an RCS format diff.
  -y  --side-by-side  Output in two columns.
    -W NUM  --width=NUM  Output at most NUM (default 130) print columns.
    --left-column  Output only the left column of common lines.
    --suppress-common-lines  Do not output common lines.
  -D NAME  --ifdef=NAME  Output merged file to show `#ifdef NAME' diffs.
  --GTYPE-group-format=GFMT  Similar, but format GTYPE input groups with GFMT.
  --line-format=LFMT  Similar, but format all input lines with LFMT.
  --LTYPE-line-format=LFMT  Similar, but format LTYPE input lines with LFMT.
    LTYPE is `old', `new', or `unchanged'.  GTYPE is LTYPE or `changed'.
    GFMT may contain:
      %<  lines from FILE1
      %>  lines from FILE2
      %=  lines common to FILE1 and FILE2
      %[-][WIDTH][.[PREC]]{doxX}LETTER  printf-style spec for LETTER
        LETTERs are as follows for new group, lower case for old group:
          F  first line number
          L  last line number
          N  number of lines = L-F+1
          E  F-1
          M  L+1
    LFMT may contain:
      %L  contents of line
      %l  contents of line, excluding any trailing newline
      %[-][WIDTH][.[PREC]]{doxX}n  printf-style spec for input line number
    Either GFMT or LFMT may contain:
      %%  %
      %c'C'  the single character C
      %c'\OOO'  the character with octal code OOO

  -l  --paginate  Pass the output through `pr' to paginate it.
  -t  --expand-tabs  Expand tabs to spaces in output.
  -T  --initial-tab  Make tabs line up by prepending a tab.

  -r  --recursive  Recursively compare any subdirectories found.
  -N  --new-file  Treat absent files as empty.
  --unidirectional-new-file  Treat absent first files as empty.
  -s  --report-identical-files  Report when two files are the same.
  -x PAT  --exclude=PAT  Exclude files that match PAT.
  -X FILE  --exclude-from=FILE  Exclude files that match any pattern in FILE.
  -S FILE  --starting-file=FILE  Start with FILE when comparing directories.
  --from-file=FILE1  Compare FILE1 to all operands.  FILE1 can be a directory.
  --to-file=FILE2  Compare all operands to FILE2.  FILE2 can be a directory.

  --horizon-lines=NUM  Keep NUM lines of the common prefix and suffix.
  -d  --minimal  Try hard to find a smaller set of changes.
  --speed-large-files  Assume large files and many scattered small changes.

  -v  --version  Output version info.
FILES are `FILE1 FILE2' or `DIR1 DIR2' or `DIR FILE...' or `FILE... DIR'.
If --from-file or --to-file is given, there are no restrictions on FILES.
If a FILE is `-', read standard input.