Sunday, 3 August 2014

how to get database data in django view and send to template

Standard
now i will describe how to implement model and template in a view in django

this is so easy and simple follow some rules thats all

ok now take a cocktail and start your coding

we will try to create a user page, first open urls.py file in your editor and add bellow code :

urlpatterns = patterns('',(r'^$', main_page),(r'^user/(\w+)/$', user_page),)



this is simple here have two url rules one for home page and other for user page

lets' write the actualy view for this app now open your views.py file in editorand add this code in your view

1. from django.http import HttpResponse, Http404
2. from django.contrib.auth.models import User
3. def user_page(request, username):
4.    try:
5.       user = User.objects.get(username=username)
6.    except:
7.       raise Http404('Requested user not found.')
8.    product = user.product_set.all()
9.    template = get_template('user_page.html')
10.  variables = Context({
                      'username': username,
                      'product': product
                      })
11.  output = template.render(variables)
12.  return HttpResponse(output)


  • user_page takes an extra parameter request object. and username from url
  • i have used User.objects.get to obtain the user object whose username is requested. We can use a similar technique to query any table by a unique column. This method throws an exception if there are no records that match the query, or if the matched record is not unique.
  • If the requested username is not available in the database, i have generate a 404 "Page Not Found" error by raising an exception of the type Http404.
  • To obtain the list of product for a particular user object, we can conveniently use the product_set attribute available in the user object. Django detects relations between data models and automatically generates such attributes. There is no need to worry about construct
next create a template in templates folder

<html>
<head>
<title>Django product - User: {{ username }}</title>
</head>
<body>
<h1>product for {{ username }}</h1>
{% if product %}
<ul>
{% for prod in product %}
<li><a href="{{ product.link.url }}">
{{ product.title }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No product found.</p>
{% endif %}
</body>
</html>


save this code in user_page.html

here {{variable}} this is for variable and {%this is for condition and loop%}
 ok now your cocktail is prepare so time to drink ,
start your server and open browser and type
http://localhost:8000/user/your_username

i think this is your first cocktail that mixed by orange juice.

enjoy