Tampilkan postingan dengan label Python. Tampilkan semua postingan
Tampilkan postingan dengan label Python. Tampilkan semua postingan

Senin, 28 Juli 2014

Using Templates in Django | Python in Web development - Part 3

In previous part of this tutorial series, we show how you can create simple web application using Django. how to develop basic and very first Website using Django.

In this post we are going to see ho we can use Templates in Django to render HTML code on Web page. Initially we hard coded the HTML part in views (views.py)

Let's start with very basic idea about how template works. Goto the directory you created in previous part(or any other Django project) and run python manage.py shell (It is necessary that you open terminal using this command)

Run the following commands,

What we have done is,
  1. Imported template module.
  2. Created template using Template() method. Everything inside the '{{}}' are variables. In our example we have two variables name and age.
  3. To assign value to this variable, we used Context() method, which takes python dictionary as argument.
  4. Now we render the template using render() method. It takes template.Context as argument and return Unicode String. You can render Template with various Context.

Now to use this in Project. you can write following code in your views.py.

views.py
from django.http import HttpResponse
from django.template import Template, Context

def first_project(request):
return HttpResponse("<h3>Welcome to my First Project</h3>")

def hello(request):
list_books = ['one','two','three']
html = """
<html>
<head><title>Homepage | Ronak khunt</title></head>
<body>
<h1>Welcome {{ uname }}</h1>
<ol>
{% for book in list_books %}
<li>{{book}} ell</li>
{% endfor %}
</ol>
</body></html>
"""
t = Template(html)
c = Context({"uname":'Ronak','list_books':list_books})
return HttpResponse(t.render(c))

Open your urls.py and set URL for this(hello()) method/View. Also note the use of for loop. Using template does not solve the problem of hard coded HTML.

To solve this problem Django provides get_template() method. Before using this method you have set TEMPLATE_DIRS in your settings.py. Open settings.py and add path to directory in which you want to store your HTML files.

settings.py
......
......
#Don't forget trailing comma at the end.

TEMPLATE_DIRS = (
'/home/user/django/first_project/templates',
)
......
......

Now create hello.html file in template directory(you have to create this Dir.) and write any code in it. In our case we will write following code.

hello.html
<html>
<head><title>Homepage | Ronak khunt</title></head>
<body>
<h1>Welcome {{ uname }}</h1>
<ol>
{% for book in list_books %}
<li>{{book}} ell</li>
{% endfor %}
</ol>
</body>
</html>

Now open views.py file of your project and add following method.

views.py
#import get_template
from template.loader import get_template
#other import statement
...

def first_project(request):
...
def hello(request):
...

def hello2(request):
t = get_template('hello.html')
c = Context({"uname":'Ronak','list_books':list_books})
html = t.render(c)
return HttpResponse(html)

Open your urls.py and set URL for this(hello2()) method/View.

Django also provides shortcut for this. You can use following method as shortcut.

views.py
#import render()
from django.shortcuts import render
#other import statement
...

def first_project(request):
...
def hello(request):
...
def hello2(request):
...

def hello3(request):
return render(request, 'hello.html',
{"uname":'Ronak','list_books':list_books})

We will also set URL for this(hello3()) View. at the your urls.py will look someting like this.

urls.py
from django.conf.urls.defaults import patterns, include, url
from firstproject.views import first_project, hello, hello2, hello3

urlpatterns = patterns('',

url(r'^first_project/$',first_project),
url(r'^hello/$',hello),
url(r'^hello2/$',hello2),
url(r'^hello3/$',hello3),

)

That is all about using template in Django.

Was this Information helpful?

Yes No


Sabtu, 05 Oktober 2013

Django: How to use Python in Web Application Development- Part 2

In this post I am going to demonstrate how to develop basic and very first website using Django - A Python Web Framework. First of all, You need to have Python and Django installed on your machine. In my previous post I have already explained how to install Django on both Linux and Windows. After installation is completed, you can start your first project.

For better understanding create new directory for Django(just for convenience). To start project run django-admin.py startproject firstproject command in your working directory. ("firstproject" is just a name of Project, you can replace it with any name).

It will create project directory named firstproject. There will be two directory, Outer firstproject and Inner firstproject. If you are using Linux you have to change permission of every single file and directory. To do this, Goto firstproject directory and run chmod 777 * command.Again goto inner firstproject directory and run the same command.

Outer firstproject directory contains manage.py and inner firstproject directory.

  • manage.py is a command line utility. you can run python manage.py help commnad for help.

  • Inner firstproject directory contains another four files.

Now we will create our first module. Create file named views.py in the Inner firstproject diretory. You can give any name to this file but, it is good convention to call it views.py.

Write the following code in this file.(line starting with '#' is comment line)

views.py#bellow statement will import HttpResponse class from
#django.http module

from django.http import HttpResponse

#Following lines of code define function named "first_project".
#function accepts one argument request. And return HttpResponse
# object which contains string.

def first_project(request):
    return HttpResponse("<h3>Welcome to my First Project</h3>")

Now we have written simple module, But our Django project do not about module we've just created. To explicitly join this module with our project we have to assign particular URL to this module.

To configure URL open urls.py file, which resides in inner firstproject directory.

If we remove comments line it only contains following:

urls.py#Line below import patterns, url and include function from
#django.conf.urls.defaults module

from django.conf.urls.defaults import patterns, include, url

#line written below will import function first_project from
#module views, which we just created above.

from firstproject.views import first_project
urlpatterns = patterns('',
)

Now to configure our module, we will add url(r'^first_project$',first_project) line as argument to patterns function. Code will look something like this.

urls.pyfrom django.conf.urls.defaults import patterns, include, url
from firstproject.views import first_project
urlpatterns = patterns('',
    url(r'^first_project/$',first_project),
)

First argument to URL is Regular Expression and Second argument is name of function we want to call when URL is opened.

For basic understanding of Regular Expression,

  • '^' sign will match staring with first_project/(e.g. first_project/first, first_project/help etc.)
  • '$' sign will match ending with first_project/(e.g. .../first/first_project/, .../help/first_project/ etc.)
In our case it will match string "first_project".

After this our basic project is done. To run it, we have to start Django server.

  • Change to outer firstproject directory
  • run python manage.py runserver command. By default it runs our server on 8000 port.
  • Now open Web Browser and type 127.0.0.1:8000 in addressbar.

If every thing works fine, You should see output "Welcome to my First Project". That's it !! this is your first Web application/Web Site using Django Framework.

Here we have simply returned plain text as response. But for real web site you have HTML code to be rendered on your page.

In the Next part of this tutorial we are going to discuss how you can use template to display/render HTML code on your website. Visit next part at: Using Templates in Django | Python in Web development - Part 3

Was this Information helpful?

Yes No


Selasa, 24 September 2013

How to install Python on Windows 7?

If you have Linux installed on your machine, python is already installed on your machine. To install Python on Windows Platform follow the steps given below:

How to install python on Windows?

  • step-1: Download python for windows from http://www.python.org/download/releases/2.7.3/(Download MSI installer).
  • step-2: Run installer and it will install python into c:\python27(number 27 may vary according to version installed).
  • step-3: Now we have to add environment variable for python. For this Goto: Control Panel > User Accounts > Change my environment variable( you can also Goto: Computer > System Property > Advance system setting > environment variables).
  • step-4: Then create New(or edit existing) variable named "path" and give value c:\python27. You also need to add C:\python27\Scripts to your path value (you can provide more than one value separated by semi-colon ).
  • step-5: Now type python in command line window and you will go into python prompt(it will be like ">>>").

If you do all the step correctly then python is installed successfully on your Computer.

See how to create twitter bot using Python at:The Python Tutorial for Twitter Bots

Was this Information helpful?

Yes No


Sabtu, 11 Mei 2013

Django: How to use Python in Web Application Development

Since last few weeks I have been Searching about How to develop Web Application using Python ?. Then I found solution to this question.

To use Python in Web Application or Web Development, you have to use Python Framework like Django, Pylons, web2py etc.

One of very Famous Framework is Django which is updated regularly. It is open source project. Web Application is very easy to develop with Django. Since Django is Python Framework, you have to have Python installed on your machine to run Django.

Python is directly available on Linux. To install python on Windows visit How to install Python on Windows platform (If you are using windows, I insist to have look at this post and check for necessary environment variables). Now i Suppose you have python installed on your Machine.

There are two version of Django available to you.

  1. The latest official release and
  2. the development version.

Note: Official release is tested and stable version, while Development version contains latest features of Django.

Now download any version from https://www.djangoproject.com/download/.

How to Install Django on Windows and Linux?

Now for Linux run following Command to Install Django:

  • tar xzvf Django-1.5.1.tar.gz(Unzip the compressed file).
  • cd Django-1.5.1(Directory name may vary as per versino.)
  • sudo python setup.py install(terminal will ask for root password).

And For Windows

  • Unzip the tar file using 7-zip or other software.
  • Goto to directory that contains setup.py file.
  • Run python setup.py install command.

Now Django is installed on your Machine.To check installation Go to your Python interpreter then:

  • run import django command.
  • then run django.VERSION command.
  • You should see output: (1, 5, 1, 'final', 0) (Which shows version of Django on your Machine).

To Develop Website using Django you should have basic knowledge of Python.

In Second part, I have described, In Detail, How to Create very Basic and First Web Application using Django Web Framework

Django is very famous for its documentation, So you can Start developing Website using this Framework. Documentation is available at https://docs.djangoproject.com/. Another Useful link is https://www.djangobook.com/


Was this Information helpful?

Yes No


Kamis, 18 April 2013

How to use rst2pdf tool on Windows and Linux

In this post I am gonna write basic tutorial on how create PDF using Rst2pdf tool on windows or linux. Rst2pdf can generate very rich quality PDFs from lightly marked up text files(.rst).

It can be installed easily.On Ubuntu linux you can install it using "Ubuntu software centre". To see how to install rst2pdf on windows visit my previous post How to install rst2pdf on Windows platform . Now I Suppose you have rst2pdf installed on your Computer.

I have explained the code in Following code itself. Browse through the code and read carefully. You might also like to see output PDF file simultaneously(link:how to use rst2pdf - example file).

Note: Space and NewLine is most important in this language.

Input:

Example File
============
.. contents::

.. section-numbering::

.. footer::

Page: ###Page###/###Total###, Example file.

Section/Header 1
----------------

Texts underlined with '=' will be main header and
Texts underlined with '-' are Sub-section.

Sub-section
~~~~~~~~~~~

Texts underlined with '~' will be Sub-sub-section

Text format
------------

Texts enclosed within **bold** will be Bold.
And those enclosed within *italic* will be Italicized

* ``Texts in double block-quote`` will lok different.

Auto numbering
~~~~~~~~~~~~~~
#. '#' will number the line automaticaly
#. this will be line number 2.

Images
~~~~~~

.. image:: logo.png

you can specify attribute of image also

.. image:: logo.png
:height: 140px
:width: 250px
:scale: 100
:alt: alternate text

you can put inline images also:

Assuming |logo.png| is already there on your machine.

.. |logo.png| image:: logo.png
:height: 10px
:width: 10px

Block
~~~~~

* you can put any text like command in box using '::'.
For example, to convert .rst to PDF enter following command ::

rst2pdf myFile.rst

* you can number the line as follow:

.. code-block:: c
:linenos:

#include
int main() {
printf("Hello World\n");
return 0;
}

Links
~~~~~

**Links** can be put in following manner

My Blog ``_

you can put **reference link** like this way.
For example, you can visit my blog [#]_

.. [#] `<http://khuntronak.blogspot.com/>`_

Lists
~~~~~

* a bullet point using "*"

- a sub-list using "-"

+ yet another sub-list

- another item

Copy this code into file myFile.rst and Execute rst2pdf myFile.rst and it will generate myFile.pdf.

You can also run rst2pdf myFile.rst -o outputFileName.pdf .
You can see the output PDF file how to use rst2pdf - example file here.

There are many other things you can do with this markup language/


Kamis, 04 April 2013

How to install rst2pdf tool on Windows 7?

rst2pdf is a tool for transforming reStructuredText to PDF using ReportLab. To install rst2pdf on windows you also need python because rst2pdf is coded in python.

If you are working on Linux, Python is already installed on your machine. To know how to install python on windows visit my post on How to install python on windows?

How to install rst2pdf on Windows?

Now download rst2pdf source from https://code.google.com/p/rst2pdf/downloads/list.

  • step-1:Unzip the source and copy this folder into C:\ location.
  • step-2:Goto rst2pdf source directory which contains setup.py file.
  • step-3:Run python setup.py install command and it will be installed.

To convert any .rst file to PDF file Run rst2pdf myfile.rst command and you are done.

To learn how to write reStructuredText (.rst) file visit my post How to use rst2pdf tool to Create PDf file on windows or Linux.

Was this Information helpful?

Yes No