To create the templates, add a folder named “templates” under the “books” application. In which create a html name 1.html and add the following code :
<html>
<head>
</head>
<body>
<form action="/name/" method="GET"> {% csrf_token %}
<label> Enter Book name </label>
<input type=”text” name=”t1” />
<label> Enter Book ID</label>
<input type=”text” name=”t2” />
<label> Enter Book author</label>
<input type=”text” name=”t3” />
</form>
</body>
</html>
urls.py is situated under
Python27
|
jango
|
testproject
|
books
|
testproject
|
settings.py
|
urls.py
|
manage.py
|
test.db
Add the following piece of code in urls.py ,
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^name/$', 'books.views.data'),
)
urlpatterns = patterns('',
(r'^name/$', 'books.views.data'),
)
Note: The url passed as action in 1.html is defined in urls.py, which provides path to function (def) named data in views.py. Here , “data” is name of function in views.py, which is “books” application.
views.py would be defined as follows with the following code snippet :
#from __future__ import unicode_literals
from django.core.context_processors import csrf
from books.models import Books
from django.utils import timezone
from django.template.loader import get_template
def data(request):
if 't1' in request.GET and request.GET['t1']:
name = request.GET['t1']
if 't2' in request.GET and request.GET['t2']:
id = request.GET['t2']
if 't3' in request.GET and request.GET['t3']:
author = request.GET['t3']
b = Books(name=name,id=id, time_at_which_it_was_bought=timezone.now(),author=author)
b.save()
Explanation to the above code:
We need to import all the tables which we will be using in views.py.
The above code imports tables from models.py. Now we need to collect all
the data entered by user in the form and store in table named Books.
Data entered in each of the fields of the form is checked to be empty or not, and then collected by using the syntax:
if 't1' in request.GET and request.GET['t1']:
name = request.GET['t1']
The
third field “time_at_which_it_was_bought” contains the time at which
book was purchased,So we need the current time which is got using timezone.now().
b = Books(name=name,id=id, time_at_which_it_was_bought=timezone.now(),author=author)
b.save()
No comments:
Post a Comment