Tech
Infected

Linux, OpenSource, Programming And Hacks

Oct 10, 2016

Simple Hello World page with django 1.9 in Ubuntu / Linux Mint [Beginners] [Part - 2]

Oct 10, 2016

In the First part of this tutorial we created an app named helloworld and added it to the setting.py file. Now let's continue further towads our journey to make a 'Hello World' page with django.


Urls


Let's define our url for our helloworld page. i.e. the url on clicking which brings us to our helloworld.html

first open up the urls.py file on our project directory (src)
(myenv) aman@vostro:~/myenv/src/mywebpage$ ls
__init__.py   settings.py   urls.py   wsgi.py
__init__.pyc  settings.pyc  urls.pyc  wsgi.pyc


mywebpage/urls.py/
from django.conf.urls import url

from django.contrib import admin


urlpatterns = [

    url(r'^admin/', admin.site.urls),

]

 
change it to look like this.

mywebpage/urls.py
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',include('blog.urls')),
] 

here, we have just imported include function and added this line url(r'',include('blog.urls')), to our urlpatterns. 

Next we create a brand new urls.py file in our helloworld app folder.

and copy the following in it.

helloworld/urls.py
from django.conf.urls import url
from . import views
import django.contrib.auth.views

urlpatterns = [
    url(r'^hello$', views.helloworld, name='helloworld'),
]


this pattern says a url which ends with hello
that will be 127.0.0.1/hello

Working with Views


views.py is a file that handles what we are going to see when we visit a particular url.

let's open up the views.py file which is inside the helloworld app

helloworld/views.py
from django.shortcuts import render

# Create your views here.



Initially there is nothing much here.

Lets write our first view!

helloworld/views.py
from django.shortcuts import render

# Create your views here.

def helloworld(request): #server takes a request
    return render(request,'helloworld.html',{}) #and returns something back

the two empty curly braces are is just an empty dictionary that is used to put variable on templates.

If you try running the server now and visit 127.0.0.1/
you should get the following error. TemplateDoesNotExist at /

so, we need to create templates!

Create Templates

Create a folder named templates inside helloworld app. and then inside of templates folder create a file named helloworld.html open helloworld.html and put some html code in it.

helloworld/templates/helloworld.html
<h1>Hello world</h1>
Now, Run your server
(myenv) aman@vostro:~/myenv/src$ python manage.py runserver
visit 127.0.0.1:8000/hello and you should see the hello world page!


No comments:

Post a Comment