Python-Django/C2/Creating-Views-and-Designing-URLs/English
Title of script:Creating Views and Design URLs
Keywords: Video tutorial, Django view, URL routing scheme
Visual cue | Narration |
Slide: Creating Views and Designing URLs | Hello and welcome to the spoken tutorial on “Creating Views and Designing URLs” |
Slide: Learning Objectives | In this tutorial, we will learn to:
|
Slide: System Requirements | To record this tutorial, I am using
|
Slide: Prerequisites | To follow this tutorial, you need to know
|
Slide: What is a view? |
|
Open a Terminal window
Press CTRl+ALT+T simultaneously |
Let us open the terminal by pressing Ctrl, Alt and T keys simultaneously on our keyboard. |
[Terminal]
|
Now using cd command, go to the folder my hyphen django which we had created earlier. |
[Terminal]
Type source myapp_env/bin/activate and press Enter |
Let us activate the virtual environment myapp underscore env
Type source <space> myapp underscore env slash bin slash activate And press Enter. |
[Terminal]
cd mysite and Press Enter |
Now let us go to the mysite folder by typing
cd <space> mysite and press Enter. |
Here onwards, please remember to press the Enter key after typing each command. | |
[Terminal] | In previous tutorial, we have used Admin app for our app models |
[Terminal]
Type gedit blog/views.py & [Enter] |
To create a view for blog app,
Type gedit <space> blog slash views dot py <space> ampersand |
[views.py]
Highlight from django.shortcuts import render # Create your views here. |
We are now in views.py file
Let us understand the written code later, because we will use render later. |
[views.py] Type:
from django.http import HttpResponse def index(request): return HttpResponse("Hello World") |
Now, let us create a simple view and see how it works.
Type the code as shown here. |
[views.py]
Highlight def index(request): |
Here, we have defined a function named index. |
[views.py]
Highlight def index(request): |
Each view function takes an Http Request object as its first parameter.
Here I have named the parameter as request. |
[views.py]
from django.http import HttpResponse Highlight HttpResponse |
HttpResponse class lives in the django dot http module. |
[views.py]
Highlight from django.http import HttpResponse |
For that, we import HttpResponse from django dot http module |
[views.py]
Highlight return HttpResponse("Hello World") |
Here, the view returns the HttpResponse as Hello World |
[views.py]
Highlight from django.http import HttpResponse def index(request): return HttpResponse("Hello World") |
This is the simplest view, we have created in Django. |
Press Ctrl+S | Save the file. |
Switch to Terminal | Switch back to the terminal. |
[Terminal]
Type gedit blog/urls.py & and press Enter |
To call the view, we need to map it to a URL.
For this we need a URL configuration. Create a file called urls dot py in blog app directory Type gedit <space> blog slash urls dot py <space> ampersand |
[blog/urls.py] Type:
from django.urls import path from . import views urlpatterns = [ path('index/', views.index, name='index'), ] |
We are now in urls.py file in blog app directory.
Let us add our first URL pattern as shown here. |
[blog/urls.py]
Highlight urlpatterns = [ |
The URL patterns determine which view will be called. |
[blog/urls.py]
Highlight from django.urls import path |
For that, we need to import path from django.urls modules |
[blog/urls.py]
Highlight path |
path function allows to route URLs to view. |
[blog/urls.py]
Highlight path('index/', views.index, name='index'), |
The arguments of the path function are route, view, and namespace |
[blog/urls.py]
Highlight path('index/', views.index, name='index'), |
The route argument should be a string that contains a URL pattern.
Here index slash is the route argument. |
[blog/urls.py]
Highlight path('index/ ', views.index, name='index') |
The view argument is blog’s view function that to map with URL.
Here, the path routes the view function index to the URL mentioned. |
[blog/urls.py]
Highlight path('index/', views.index, name='index'), |
The name argument is used to identify the URL.
It is used to perform URL reversing. We shall understand this in later tutorials. |
[blog/urls.py]
Highlight from . import views |
We import views from the blog app. |
[blog/urls.py] | We have now created blog app urls dot py.
It will hold all the URLs related to our blog application. |
Press Ctrl+S | Save the file. |
Switch to Terminal | Switch back to the terminal. |
[Terminal]
Type ls mysite [Enter] |
Now type ls <space> mysite |
[Terminal]
Highlight urls.py |
We see the project’s URL.
We need to include app’s URLs in the mysite’s URL that is the root URL. |
[Terminal]
Type gedit mysite/urls.py & and press Enter |
Clear the terminal
Let us open the url.py file located under mysite folder. Type gedit <space> mysite slash urls dot py <space> ampersand |
[mysite/urls.py]
Highlight from django.urls import path |
We are in now in root urls.py file
Note that, it already imported the django.urls.path module. |
[mysite/urls.py]
Type path('blogs/', include('blog.urls', namespace='blogs')) |
We need to include our blog app URLs in the urlpatterns list.
In the urlpatterns list value, type as shown. |
[mysite/urls.py]
Highlight path('blogs/', include('blog.urls', namespace=’blog’)), |
Here, we added app name blogs as a route argument. |
[mysite/urls.py]
Highlight path('blogs/', include('blog.urls', namespace='blog')), |
include function takes a full Python import path to another URL configuration module.
In our case it is the blog apps URL. |
[mysite/urls.py]
Highlight from django.urls import path, include |
For that we need to import include from django.urls module.
So in the line from django.urls import path add comma space include |
[mysite/urls.py]
Highlight path('blogs/', include('blog.urls', namespace='blog')), |
Naming URL patterns is not to clash with other applications’ names. |
Press Ctrl + S | Save the file and switch to the blog’s App urls.py file. |
[blog/urls.py]
Type app_name = 'blog' |
We need to include app underscore name as blog before the beginning of URL pattern.
Type the code as shown here. |
[blog/urls.py]
Highlight app_name = 'blog' |
Django uses it to look for the matching application namespace in the URL file in Root directory. |
Switch back to Terminal | We have now included view from blog application
. Save the file and switch back to Terminal. |
[Terminal]
Run the server Type python manage.py runserver and press Enter |
Let's run the Django development server.
Type python <space> manage dot py <space> runserver |
Open a browser and type
localhost:8000/blogs/index |
Now, open a web browser and type
localhost:8000/blogs/index |
[Browser]
Output: “Hello World” |
Here, we can see the text "Hello World", which is defined in the index view. |
Switch back to editor blog/views.py | Let us add few more lines to display our blog object that we created in the previous tutorial.
Now, switch back to views dot py file in the text editor. |
[views.py]Type:
def get_blogs(request): blogs = Blog.objects.all() return HttpResponse(blogs) |
Now below the index function, let us define a new function get underscore blogs
Type the code as shown here. |
[views.py]
Type from .models import Blog |
To get the Blog objects, we need to import Blog from models.
So next to the line importing HttpResponse, type the code as shown here- from dot models import Blog |
[views.py]
Highlight def get_blogs(request): |
The function get underscore blogs will give the blog object. |
[views.py]
Highlight blogs = Blog.objects.all() |
This is a query, which gets all objects in Blog model.
We will learn about this in detail in the upcoming tutorials. |
[views.py]
Highlight return HttpResponse(blogs) |
Then, the view returns the blog objects. |
Press Ctrl + S | Save the file |
[views.py]
Switch to blog/urls.py editor from blog/views.py |
Next step to configure our view with URL.
For that, switch to the blog app’s url.py file in the text editor. |
[blog/urls.py]
path('get_blogs/',views.get_blogs, name='get_blogs'), |
We are now in urls.py file in blog app.
Insert the path for get underscore blogs in the URL pattern list. |
[blog/urls.py]
Highlight path('get_blogs/',views.get_blogs, name=’get_blogs') |
Views dot get underscore blogs function is assigned to the URL get_blogs |
[blog/urls.py]
Highlight name='get_blogs' |
The last part name equals to get underscore blogs is the name of URL used to identify the view. |
Press Ctrl+S | We have modified our code to display our blog objects.
Save the file. |
Switch to Browser | Switch back to the browser. |
Open a browser and type localhost:8000/blogs/get_blogs | To call the view function get underscore blogs, on the browser, type-
localhost:8000/blogs/get_blogs And press Enter. |
[Browser]
Highlight Blog object(1) |
Here, we can see the Blog object that was created in previous tutorial. |
Switch back to Slide | Now we have created a simple client-server model. |
Slide: Client Server model |
|
Switch back to editor | Let us switch back to views dot py file in the text editor. |
[views.py]
response = 'Blogs:'for blog in blogs: response += ' |
We are now in views dot py file.
Let us modify our view to display an individual blog . Modify the function get_blogs as shown. |
[views.py]
Highlight response = 'Blogs:' |
This is the response, that is relevant to the user. |
[views.py]
Highlight for blog in blogs: |
This for loop fetches each individual blog from the blogs list. |
[views.py]
Highlight response += ' |
Then performs a string formatting operation. |
[views.py]
Highlight '{0}'.format(blog) |
In String Format method, we pass blog as argument in bracket.
This argument is formatted into a string in the placeholder defined by a pair of curly braces. Here, we pass blog as value to the placeholder. |
[views.py]
Highlight += |
Plus equal to performs string concatenate operation.
Here, blog values are assigned to response. |
[views.py]
Highlight return HttpResponse(response) |
The return statement will return all Blog objects in blog as a response. |
Press Ctrl + S | We have altered our views to get an individual blog.
Save the file. |
Switch to Browser | Now, switch to the browser. |
[browser]
Press ctrl+r |
The modified server reloads when the views are modified and saved.
So, reload the web page to update the changes. |
[browser]
Highlight Blogs: Blog object(1) |
Now, it is only displaying the blog objects |
Let us switch to views dot py file in the text editor. | |
[views.py]
articles = Article.objects.filter(blog=blog)response += ','.join([article.title for article in articles]) |
Now let us add a code to display articles related to a blog in the view.
Before the get underscore blogs return statement, type the code as shown here. |
[views.py]
Highlight articles = Article.objects.filter(blog=blog) |
This query will filter the Article objects related to Blog model.
Query has the general form of “object = Model.objects.get(id=id)” |
[views.py]
Highlight response += ','.join([article.title for article in articles]) |
The next statement will concatenate the Article object with respect to the Blog object |
[views.py]
Highlight from .models import Blog, Article |
To do this, we have to import Article from our Models.
So in the line from dot models import Blog add comma Article. |
[views.py]
Highlight return HttpResponse(response) |
Now this return function will return both Blogs and Articles related to the blog model. |
Press Ctrl + S | We have now edited the view to display Articles related to a Blog.
Save the file |
Switch back to browser. | Switch back to the browser. |
[browser] Press ctrl+r
Highlight Blogs: Blog object(1) My Article |
Refresh the page.
Now we can see the My Article object which we have created in the previous tutorial. |
[Terminal]
Press Ctrl+C keys |
Let us now stop the server and deactivate the virtual environment.
Switch to the terminal and press Ctrl and C keys to stop the server. |
[Terminal]
Type deactivate [Enter] |
Then type deactivate and press Enter. |
With this, we come to the end of this tutorial.
Let us summarize. | |
Slide: Summary | In this tutorial, we have learnt about
|
Slide: Assignment | As an assignment,
|
Slide: About Spoken Tutorial project | The video at the following link summarises the Spoken Tutorial project.
Please download and watch it. |
Slide: Spoken Tutorial workshops | The Spoken Tutorial Project team conducts workshops and gives certificates.
For more details, please write to us. |
Slide: Forum for specific questions: | Please post your timed queries in this Forum. |
Slide: FOSSEE to answer questions | Please post your general or technical questions in this Forum. |
Slide: Acknowledgement | Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.
More information on this mission is available at this link. |
Slide: Thanks Slide | This script has been contributed by Thiagarajar College of Engineering and the FOSSEE Project, IIT Bombay.
The video has been recorded by Praveen from Spoken Tutorial Project, IIT Bombay. Thanks for watching. |