Saturday, January 11, 2014

Views

Now that we have created our admin page, we'll move on to adding webpages to our website. Feel free to tinker with the admin page, django offers amazing tools for admin documentation and control. But more on that later.
In our website, when someone clicks on a hyperlink, or does some action (specified by us) that triggers a URL change, they should be redirected to a new page. Creating this new page has two aspects: 1) Creating the user interface (in the views.py file)  2) Creating a custom URL to guide the user to that page.
As I mentioned earlier in this tutorial, I'm assuming a rudimentary knowledge of HTML, PHP, JavaScript and other web design tools. With that in mind, we'll dive straight into the GUI design.
Let's design our homepage first. Open the views.py file.

Type the following on the first line:
from django.http import HttpResponse

HTTP stands for 'Hyper Text Transfer Protocol'. The HttpResponse () function will render whatever HTML/PHP/JavaScript/CSS code we write onto the browser to make a GUI.

Now type the following code:
def home (request):
      someCode = """
      <html>
         <body>
            Hello World!
         </body>
        </html>
       """
       return HttpResponse (someCode)

Now your homepage is all set to display the ageless 'Hello World!' message. Note: The 'request' parameter is very important.
Now that we have our GUI up and running (I know it's not very impressive but you can add beauty later. Right now what we need to focus on is redirecting) we'll proceed to step 2: creating a URL.
Open the urls.py file and type the following code:
url (r'^home/', 'website.views.home'),

This code will tell django that if the URL 'localhost/home' is accessed, the code in the function home() in the app website's views.py file is to be used as GUI.
The r'^' is a part of UNIX regular expressions, about which you can read up online. But in depth knowledge of that is not required here. r'^' indicates that in localhost/home, 'localhost' can be replaced with anything (when it is deployed on the server) and the result won't change. You can put your site's domain name in place of that.
Now when you type http://127.0.0.1/home/ in your browser, you will see this 'Hello World!' message.
That's all for now! 

No comments:

Post a Comment