Total Pageviews

Tuesday, 21 October 2014

Passing Information between pages using urls.py

Passing values from templates to views can be done by passing those values through urls. For example ,if one has liked the book ,the id of the book has to be sent to the views (to increment the number of likes) by passing id in urls. In templates ,say 3.html
             {% if books_list %}
                
    {% for b in books_list %} {{b.name}}
    Do you like this book??
    {% csrf_token %}
    {% endfor %}
{% endif %}
This provides list of all book names and a like button . On clicking like button , book id which is {{b.id}} is passed through url which is forms action. In urls.py, Add the url below in your urls.py ,which pass the book id of the book liked to views.
url(r'^like/(?P\d+)/$','books.views.like'),
The above url redirects to like function(def) of views. In view.py,
def like(request,id):
   n = Books.objects.get(id=id)
   n.likes = n.likes+1
   n.save()
The ‘likes’ of the book has to be incremented by one,by getting the book by its id (which was passed through url).

No comments:

Post a Comment