Saturday 2 August 2014

how create a besic app in django

Standard

Creating the Main Page View

A view in Django terminology is a regular Python function that responds to a page request by generating the corresponding page. To write our first Django view for the main page, we first need to create a Django application inside our project.

the following command within our store folder:

$ python manage.py startapp app

• __init__.py: This file for Python that app is a Python package.
• views.py: This file will contain our views.
• models.py: This file will contain our data models.

Now, create the main page view. Open the file store/views.py in your editor and enter the following:


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>
''' % (
'Django Store',
'Welcome to Django Store',
'This is a test view page'
)
return HttpResponse(output)

  • i have import the class HttpResponse from django.http. We need this class for generate our response page.
  • i have define a Python function that takes one parameter named request this parameter contains user input and other information. For example, request. GET, request.POST and request.COOKIES are dictionaries that contain get, post and cookie data.
  • i have build the HTML code of the response page, wrap it within an HttpResponse object and return it.

 Creating the Main Page URL

a urls.py file create when i have created project this file contain valid url for our project, lets edit this file and type this code

from django.conf.urls.defaults import *
from bookmarks.views import *
urlpatterns = patterns('',(r'^$', main_page),)

  • file imports everything from the module django.conf.urls.defaults. this module provides the necessary functions to define URLs.
  • i have import everything from store.views. This is necessary access our views, and connect them to URLs.
  • patterns function is used to define the URL table. It contains only one mapping for now — from r'^$' to our view main_page.(basic pattern are bellow table)

Symbol / ExpressionDescription
. (Dot)Any character.
^ (Caret)Start of string.
$End of string
*0 or more repetitions.
+1 or more repetitions.
?0 or 1 repetitions.
|A | B means A or B
[a-z]Any lowercase character
\wAny alphanumeric character or _
\dAny digit

now everything is clear now run your server and open
http://localhost:8000
from your browser

ready your cocktail with water