create view
Date: March 18th 2016
Last updated: March 18th 2016
A view provides an http response and can call templates to be rendered. In this example I have added a profile page and a diary entry page. Neither of them do anything special. They just render a semi-static response that adds the surfer id from the http request into a string on the page.
Things to note:
- model.py stays exactly the same
- views.py has methods that return an http response
- It is the job of urls.py to call the correct method.
update urls.py (mysite)
I'm doing this so that the default http link is the index page.
urlpatterns = [
url(r'^', include('surferprofile.urls')), #<==== change made here
url(r'^admin/', admin.site.urls),
]
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the surferprofile index page.")
def profilepage(request, surfer_id):
response = "You're looking at the profile page for %s"
return HttpResponse(response %surfer_id)
def creatediaryentry(request, surfer_id):
response = "Adding diary entry for surfer # %s"
return HttpResponse(response %surfer_id)
add to urls.py (surferprofile app)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<surfer_id>[0-9]+)/$',views.profilepage, name='profile'),
url(r'^(?P<surfer_id>[0-9]+)/diary/$',views.creatediaryentry, name='diary'),
]