Day 3 - Django Views

Today was all about learning Django views. Again, this is not a new topic for me, so I already understand how that views are simply a means to display the data stored in your models. Example: If your model contains blog posts, then the view is how to display each individual blog post. Here’s the code that was integrated in the class example:

views.py:

#from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template.context import Context

# Create your views here.
def hello(request):
name = "Jay"
html = "<html><body>Hi %s. It worked.</body></html>" % name
return HttpResponse(html)

def hello_template(request):
name = "Jay"
t = get_template('hello.html')
html = t.render(Context({'name': name}))

hello.html :

<html>
<body>

Hi , this TEMPLATE seems to have worked.

</body>
</html>

urls.py:

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_test.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^hello/', 'article.views.hello'),
url(r'^hello_template/', 'article.views.hello_template'),
url(r'^admin/', include(admin.site.urls)),
)

The magic is in the urls.py code. It’s the tie that binds the url to the models/view code. Not too exciting- it’s just next in the order of things…

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin