You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Let us create a Python application for "online poll" based on Django. The first thing you should do is changing your working directory to your project.

$ cd my_project

In order to create an app, you will need "manage.py" created by Django. Once you verify it, you can create "online poll" app by running below command.

$ python manage.py startapp polls


You will be able to see the directory structure like below if you haven't faced any error

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

So above directory will be your base camp for "online poll" application.

Creating a first view

Let us open views.py and add some codes like below.

polls/views.py
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

The above is the most simple example of view in Django. In order to call view, you should use URLconf in order to have the connected URL. What you should do is just creating a null file as urls.py. You can do it like below

$ touch urls.py

Then you should be able to see your directory structure like below

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py

And let us put below content to urls.py

polls/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

The next action you should do is creating another URLconf for your project like below.

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Now index view is integrated with URLconf. Time for you to check your server by following command like

$ python manage.py runserver

If you face an error like below, please create an empty file for admin.py on the root directory of your project

  • No labels