{"id":435145,"date":"2018-05-07T13:08:08","date_gmt":"2018-05-07T13:08:08","guid":{"rendered":"https:\/\/essaypaper.org\/writing-your-first-django-app-pdf\/"},"modified":"2018-10-24T09:00:11","modified_gmt":"2018-10-24T09:00:11","slug":"writing-your-first-django-app-pdf","status":"publish","type":"post","link":"https:\/\/www.benedictsol.com\/blogs\/writing-your-first-django-app-pdf\/","title":{"rendered":"Writing your first django app pdf"},"content":{"rendered":"<div>\n<div align=\"center\">\n\t\t\t <img decoding=\"async\" src=\"http:\/\/ihelptostudy.com\/other\/custom_top_article.gif\" alt=\"Order custom writing\"\/>\n\t\t<\/div>\n<div class=\"introimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-first-django-app-pdf_3.png\" width=\"552\" height=\"277\" alt=\"Writing your first django app pdf couple the model\" title=\"Writing your first django app pdf couple the model\"\/><\/div>\n<p>This tutorial begins where Tutorial 2 left off. We\u2019re continuing the Web-poll application and will focus on creating the public interface  &amp;\u201dviews.&amp;\u201d<\/p>\n<h2>Overview\u00b6<\/h2>\n<p>A view is a &amp;\u201dtype&amp;\u201d of Web page in your Django application that generally serves a specific function and has a specific template. For example, in a blog application, you might have the following views:<\/p>\n<ul>\n<li>Blog homepage  displays the latest few entries.<\/li>\n<li>Entry &amp;\u201ddetail&amp;\u201d page  permalink page for a single entry.<\/li>\n<li>Year-based archive page  displays all months with entries in the given year.<\/li>\n<li>Month-based archive page  displays all days with entries in the given month.<\/li>\n<li>Day-based archive page  displays all entries in the given day.<\/li>\n<li>Comment action  handles posting comments to a given entry.<\/li>\n<\/ul>\n<p>In our poll application, we\u2019ll have the following four views:<\/p>\n<ul>\n<li>Question &amp;\u201dindex&amp;\u201d page  displays the latest few questions.<\/li>\n<li>Question &amp;\u201ddetail&amp;\u201d page  displays a question text, with no results but with a form to vote.<\/li>\n<li>Question &amp;\u201dresults&amp;\u201d page  displays results for a particular question.<\/li>\n<li>Vote action  handles voting for a particular choice in a particular question.<\/li>\n<\/ul>\n<p>In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views). Django will choose a view by examining the URL that\u2019s requested (to be precise, the part of the URL after the domain name).<\/p>\n<div align=\"center\"> <img decoding=\"async\" src=\"http:\/\/ihelptostudy.com\/other\/essay-468.gif\" alt=\"Low cost essay writing\"\/><\/div>\n<p>Now in your time on the web you may have come across such beauties as &amp;\u201dME2\/Sites\/dirmod.asp?sid=type=genmod=Core+Pagesgid=A6CD4967199A42D9B65B1B&amp;\u201d.<!--image2begin-->\n<\/p>\n<div class=\"middleimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-first-django-app-pdf_2.png\" width=\"600\" height=\"420\" alt=\"Writing your first django app pdf The template system uses dot\" title=\"Writing your first django app pdf The template system uses dot\"\/><\/div>\n<p><!--image2end--> You will be pleased to know that Django allows us much more elegant URL patterns than that.<\/p>\n<p>A URL pattern is simply the general form of a URL \u2013 for example: \/newsarchive\/year\/month\/ .<\/p>\n<p>To get from a URL to a view, Django uses what are known as \u2018;URLconfs\u2019. A URLconf maps URL patterns (described as regular expressions) to views.<\/p>\n<p>This tutorial provides basic instruction in the use of URLconfs, and you can refer to django.urls for more information.<\/p>\n<h2>Writing more views\u00b6<\/h2>\n<p>Now let\u2019s add a few more views to polls\/views.py. These views are slightly different, because they take an argument:<\/p>\n<p>Wire these new views into the polls.urls module by adding the following url() calls:<\/p>\n<p>Take a look in your browser, at &amp;\u201d\/polls\/34\/&amp;\u201d. It\u2019ll run the detail() method and display whatever ID you provide in the URL. Try &amp;\u201d\/polls\/34\/results\/&amp;\u201d and &amp;\u201d\/polls\/34\/vote\/&amp;\u201d too  these will display the placeholder results and voting pages.<\/p>\n<p>When somebody requests a page from your website  say, &amp;\u201d\/polls\/34\/&amp;\u201d, Django will load the mysite.urls Python module because it\u2019s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the regular expressions in order. After finding the match at \u2018^polls\/\u2019. it strips off the matching text ( polls\/ ) and sends the remaining text  34\/  to the \u2018;polls.urls\u2019 URLconf for further processing.<!--image3begin-->\n<\/p>\n<div class=\"3rdimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-first-django-app-pdf_1.png\" width=\"524\" height=\"276\" alt=\"Writing your first django app pdf After finding the\" title=\"Writing your first django app pdf After finding the\"\/><\/div>\n<p><!--image3end--> There it matches r\u2019^(?Pquestion_id[0-9]+)\/$\u2019. resulting in a call to the detail() view like so:<\/p>\n<p>The question_id=\u201934\u2019 part comes from (?Pquestion_id[0-9]+). Using parentheses around a pattern &amp;\u201dcaptures&amp;\u201d the text matched by that pattern and sends it as an argument to the view function; ?Pquestion_id defines the name that will be used to identify the matched pattern; and [0-9]+ is a regular expression to match a sequence of digits (i.e. a number).<\/p>\n<p>Because the URL patterns are regular expressions, there really is no limit on what you can do with them. And there\u2019s no need to add URL cruft such as .html  unless you want to, in which case you can do something like this:<\/p>\n<p>But, don\u2019t do that. It\u2019s silly.<\/p>\n<h2>Write views that actually do something\u00b6<\/h2>\n<p>Each view is responsible for doing one of two things: returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.<\/p>\n<p>Your view can read records from a database, or not. It can use a template system such as Django\u2019s  or a third-party Python template system  or not. It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.<\/p>\n<p>All Django wants is that HttpResponse. Or an exception.<\/p>\n<p>Because it\u2019s convenient, let\u2019s use Django\u2019s own database API, which we covered in Tutorial 2. Here\u2019s one stab at a new index() view, which displays the latest 5 poll questions in the system, separated by commas, according to publication date:<\/p>\n<p>There\u2019s a problem here, though: the page\u2019s design is hard-coded in the view. If you want to change the way the page looks, you\u2019ll have to edit this Python code. So let\u2019s use Django\u2019s template system to separate the design from Python by creating a template that the view can use.<\/p>\n<p>First, create a directory called templates in your polls directory. Django will look for templates in there.<\/p>\n<p>Your project\u2019s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a &amp;\u201dtemplates&amp;\u201d subdirectory in each of the INSTALLED_APPS .<\/p>\n<p>Within the templates directory you have just created, create another directory called polls. and within that create a file called index.html. In other words, your template should be at polls\/templates\/polls\/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls\/index.html .<\/p>\n<p>Now we might be able to get away with putting our templates directly in polls\/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.<\/p>\n<p>Put the following code in that template:<\/p>\n<p>The get_object_or_404() function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get() function of the model\u2019s manager. It raises Http404 if the object doesn\u2019t exist.<\/p>\n<p>Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist ?<\/p>\n<p>Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling. Some controlled coupling is introduced in the django.shortcuts module.<\/p>\n<p>There\u2019s also a get_list_or_404() function, which works just as get_object_or_404()  except using filter() instead of get(). It raises Http404 if the list is empty.<\/p>\n<h2>Use the template system\u00b6<\/h2>\n<p>Back to the detail() view for our poll application. Given the context variable question. here\u2019s what the polls\/detail.html template might look like:<\/p>\n<p>The template system uses dot-lookup syntax to access variable attributes. In the example of &gt;. first Django does a dictionary lookup on the object question. Failing that, it tries an attribute lookup  which works, in this case. If attribute lookup had failed, it would\u2019ve tried a list-index lookup.<\/p>\n<p>Method-calling happens in the  loop: question.choice_set.all is interpreted as the Python code question.choice_set.all(). which returns an iterable of Choice objects and is suitable for use in the  tag.<\/p>\n<p>See the template guide for more about templates.<\/p>\n<h2>Removing hardcoded URLs in templates\u00b6<\/h2>\n<p>Remember, when we wrote the link to a question in the polls\/index.html template, the link was partially hardcoded like this:<\/p>\n<p>The problem with this hardcoded, tightly-coupled approach is that it becomes challenging to change URLs on projects with a lot of templates. However, since you defined the name argument in the url() functions in the polls.urls module, you can remove a reliance on specific URL paths defined in your url configurations by using the  template tag:<\/p>\n<p>The way this works is by looking up the URL definition as specified in the polls.urls module. You can see exactly where the URL name of \u2018;detail\u2019 is defined below:<\/p>\n<p>If you want to change the URL of the polls detail view to something else, perhaps to something like polls\/specifics\/12\/ instead of doing it in the template (or templates) you would change it in polls\/urls.py :<\/p>\n<h2>Namespacing URL names\u00b6<\/h2>\n<p>The tutorial project has just one app, polls. In real Django projects, there might be five, ten, twenty apps or more. How does Django differentiate the URL names between them? For example, the polls app has a detail view, and so might an app on the same project that is for a blog. How does one make it so that Django knows which app view to create for a url when using the  template tag?<\/p>\n<p>The answer is to add namespaces to your URLconf. In the polls\/urls.py file, go ahead and add an app_name to set the application namespace:<\/p>\n<p>Now change your polls\/index.html template from:<\/p>\n<p><center><iframe loading=\"lazy\" width=\"420\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/XA5pBxY6fYc\" frameborder=\"0\" allowfullscreen=\"\"><\/iframe><br \/><\/center><\/p>\n<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial begins where Tutorial 2 left off. We\u2019re continuing the Web-poll application and will focus on creating the public interface &amp;\u201dviews.&amp;\u201d Overview\u00b6 A view is a &amp;\u201dtype&amp;\u201d of Web page in your Django application that generally serves a specific <a href=\"https:\/\/www.benedictsol.com\/blogs\/writing-your-first-django-app-pdf\/\" class=\"read-more\">Read More &#8230;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[15,46],"tags":[],"class_list":["post-435145","post","type-post","status-publish","format-standard","hentry","category-essay-paper-writing","category-writing"],"_links":{"self":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts\/435145","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/comments?post=435145"}],"version-history":[{"count":0,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts\/435145\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/media?parent=435145"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/categories?post=435145"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/tags?post=435145"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}