Creating Tech_projects App: Views - SethuGopalan/ebdjangoVR GitHub Wiki
need to create view functions to send the data from the database to the HTML templates
In the Tech_projects app, create two different views:
-
An index view that shows a snippet of information about each project
-
A detail view that shows more information on a particular topic
for index view, Inside views.py, import the Tech_project class from models.py and create a function Tech_project_index() that renders a template called Tech_project_index.html. In the body of this function, code to Django ORM query to select all objects in the Project table
from django.shortcuts import render from projects.models import Project
def Tech_project_index(request):
Tech_projects = Tech_project.objects.all() -here perform a query. A query a command that allows you to create, retrieve, update, or delete objects
(or rows) in your database. here retrieving all objects in the Tech_projects table.
context = { - here define a dictionary context. The dictionary only has one entry
Tech_projects to assign Queryset containing all projects.
The context dictionary is used to send information to template. Every
view function needs to have a context dictionary.
'Tech_projects': Tech_projects
}
return render(request, 'Tech_project_index.html', context) - context is added as an argument to render(). Any entries in the context dictionary are
available in the template, as long as the context argument is passed to render().
need to create a context dictionary and pass it to render in each view function
also render a template named project_index.html, which doesn’t exist yet.
create the templates for these views in the next
section.
created Tech_project_index now add Tech_project_index.html create the Tech_project_detail() view function. This function will need an additional argument: the id of the project that’s being viewed
def Tech_project_detail(request, key):
tech_project = Tech_Project.objects.get(key=key) -> this will perform another query. This query retrieves the project with primary key, key, equal to
that in the function argument,then assign that project in to context dictionary, which we pass to
render().
context = {
'tech_project': tech_project
}
return render(request, 'Tech_project_detail.html', context)