Django: Reassponding to web request.














































Django: Reassponding to web request.



View

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 views.py 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 url.py file (myproject/url.py). 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 url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, 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/url.py" 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 "Cprojecturl.py" file. So best practice is to create an  url.py" per application and to include it in our main projects url.py file (we included admin URLs for admininterface before).

How is it Done?

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



Then myproject/url.py 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/view.py "



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




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.


Comments