Advertisement
quantim

First View

Apr 16th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. Creating Django index.html
  2.  
  3. Assume a directory structure such as the following:
  4.  
  5. ~/workspace/mysite/mysite
  6. ~/workspace/mysite/siteapp
  7.  
  8.  
  9. Here is an explanation of how views work.
  10.  
  11. 1) The url matches in the mysite/urls.py
  12.  
  13. 2) any matching part is stripped off, and sent to the siteapp/urls.py
  14.  
  15. 3) a view is returned based on this match. This view is actually a function that returns
  16. an HTML template (html with variables/programming logic).
  17.  
  18. 4) We need to create the template to make sure it exists.
  19.  
  20.  
  21. //////////////////// 1 ///////////////////////////
  22.  
  23. In the mysite/urls.py add the following lines
  24.  
  25. from django.conf.urls import url, include
  26.  
  27. urlpatterns = [
  28. url(r'^mysite/', include("siteapp.urls")),
  29. ]
  30. ///////////////////// 2 ////////////////////////////
  31.  
  32. If a user types in https://www.domain.com/mysite, django will
  33. send https://www.domain.com to siteapp/urls.py file for further processing.
  34. Firstly, make sure this file exists,
  35.  
  36. $ touch ~/workspace/mysite/siteapp/urls.py
  37.  
  38. Then add the following lines
  39.  
  40. from django.conf.urls import url
  41. from . import views
  42.  
  43. urlpatterns = [
  44. url(r'^$', views.index, name='index')
  45. ]
  46.  
  47. ////////////// 3 /////////////////////////
  48.  
  49. Next, we need to make sure that ~/workspace/mysite/siteapp/views.py
  50. contains a function named index. Add the following lines to that file,
  51.  
  52. from django.shortcuts import render
  53.  
  54. # Create your views here.
  55. def index(request):
  56. return render(request, 'siteapp/index.html', {'something': 'World!'})
  57.  
  58. ////////////////// 4 ///////////////////////
  59.  
  60. The above function returns an html template located in ~/workspace/mysite/siteapp/templates/siteapp/index.html
  61. We need to make sure this file exists. The function also substitutes all occurrences of the variable "{{ something }}"
  62. with "World!".
  63.  
  64. Create the directory if it does not exist,
  65. $ mkdir -p ~/workspace/mysite/siteapp/templates/siteapp/
  66.  
  67. Then add the following lines,
  68. <!DOCTYPE HTML>
  69. {% extends "base.html" %}
  70. <html>
  71. <head>
  72. <title>MySite!</title>
  73. </head>
  74. <body>
  75. <p>Hello {{ something }}</p>
  76. </body>
  77. </html>
  78.  
  79. ////////////////////////////////////////////////
  80.  
  81. Go ahead and run the dev server and visit the page to make sure it works.
  82.  
  83. $ ./manage.py runserver 0.0.0.0:80
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement