Python 3x Pandas Django

Basic Request and Response


In this session, you’re going to see what happens when you type an address into your web browser and press Enter.

Image

User <--> URL <--> View


Let’s learn by example.

Creating helloworld app

Now that your environment – a “myfirstsite” project – is set, you’re set to start doing work.

Each application you write in Django consists of a Python package\Apps that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

Projects vs Apps

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a blog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

Your apps can live anywhere on your Python path. In this example, we’ll create our helloworld app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of 'myfirstsite’.

To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp helloworld

Image

That’ll create a directory helloworld, which is laid out like this:

myfirstsite /
    helloworld/
  	    migrations/
            __init__.py
      	__init__.py
        admin.py
        apps.py
        models.py
        tests.py
        views.py
    myfirstsite /
  	db.sqlite3
  	manage.py

I am going to use Visual Studio Code. It’s a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux. It is a small download so you can install in a matter of minutes and give VS Code a try. https://visualstudio.microsoft.com/downloads/

let's get started

Step1: Open your project folder 'myfirstsite’ in VS Code

Image


Step2: Write your first view. Open the file helloworld/views.py and put the following Python code in it:

# Create your views here.
def index(request):
    return HttpResponse("Hello, world.")

Image

You may see an error at line return HttpResponse because HttpResponse function is not imported from http Package. Add the following code:

from django.http import HttpResponse

Image

This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf.

Step3: create a URLconf in the helloworld app

To create a URLconf in the helloworld app directory, create a file called urls.py or copy urls.py from project folder myfirstsite and remove all the lines in it. Your app directory should now look like:

tutorial1/
    helloworld/
  	    migrations/
            __init__.py
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
  	    urls.py
        views.py
    myfirstsite /
  	db.sqlite3
  	manage.py

In the helloworld/urls.py file include the following code:

from django.urls import path

from . import views

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

So you will have,

Image

The next step is to point the root URLconf at the helloworld.urls module. In myfirstsite/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:

Image

The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

In this example, http://127.0.0.1:8000/helloworld/

NOTE: You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.

Step4: Run the server

You have now wired an index view into the URLconf. Verify it’s working with the following command:

python manage.py runserver

Image

Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a “Hello, World.” Page. It worked!.

Image
IMPORTANT:

The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for.

path() argument: route

route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.

For example, in our request to

https://www.example.com/helloworld/, the URLconf will look for helloworld/. In a request to https://www.example.com/helloworld/?page=3, the URLconf will also look for helloworld/ (We’ll see an example of this in a bit.)

path() argument: view

When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments - https://www.example.com/helloworld/?page=3.

In our example,

when you type an address https://www.example.com/helloworld/ into your web browser and press Enter. Django finds a matching pattern, it calls the specified view function index with an HttpRequest object as the first argument.

# Create your views here.
def index(request):
    return HttpResponse("Hello, world.")

path() argument: kwargs

Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial. https://www.example.com/helloworld/?page=3 – we will see kwargs in the upcoming examples.

HttpResponse from myfirstsite/urls.py

In myfirstsite/urls.py, add an import for from helloworld import views and insert an path() in the urlpatterns list, so you have:

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

from helloworld import views

urlpatterns = [
    path('helloworld/', include('helloworld.urls')),
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
]

Image

Go to http://localhost:8000/ in your browser, and you should see the text “Hello, world.”, which you defined in the index view.

Image

Congratulations! You have successfully completed basic Django request and response tutorial session. Let us move to the next topic Django Models.

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!