Django: Reassponding to web request.

Django: Reassponding to web request.


A view function is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page.

In Django, views have to be created in the app file.

Simple View

We will create a simple view in myapp to say "hello world"

before this, we will make template, which contain html file to be run. making 'template' dir in 'myapp/' then adding 'home.html'-

Now linking adding into views-

Django - URL Mapping

Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project file (myproject/ When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the file, and then return the HTML response or a 404 not found error, if not found. In, the most important thing is the "urlpatterns" tuple. It's where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like -

Organizing Your URLs

So far, we have created the URLs in "myprojects/" file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the "" file. So best practice is to create an" per application and to include it in our main projects file (we included admin URLs for admininterface before).

How is it Done?

We need to create an file in myapp using the following code -

Then myproject/ will change to the following -

Sending Parameters to Views

We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via "/articles/article_id"

Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in "Cmyapp/ "

We want to map it in myapp/ so we can access it via "/myapp/article/articleId", we need the following in "myapp/" -

When Django will see the url: "/myapp/article/42" it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result-

Congratulations you successfully understand hoe to respond to web request.