Before we dive into creating our first URL and view, let's clarify some key concepts:
Route: In Django, a route leads us to a specific resource by creating the path part of a URL. This routing is defined in the urls.py file(s) located in the Django project root directory and/or inside application directory(s).
View: A view is the logic that handles a request and returns a response. In Django, views are typically defined as functions or classes within the views.py file of an application directory. Views contain the actions and business logic that are executed when a URL is accessed.
Step-By-Step Setup Of Our First URL http://example.com/challenges/january
Let's create our first URL and view in Django. We'll set up a simple "January challenge" page.
1. Create the View
First, let's create our resource. Open the views.py
file in your app directory (let's assume we have an app called 'challenges') and add the following code:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, this is the January challenge!")
This view function does two things:
- It accepts a
request
object, which is automatically generated by Django when a user accesses the URL. - It returns a simple HTTP response with our message.
NOTE: In this basic example, we're not doing anything with the request object. We're just accepting it and returning a response.
2. Create the URL Pattern
Next, we need to map this view to a URL. Create a new file called urls.py
in your app directory (if it doesn't exist already) and add the following:
from django.urls import path
from . import views
urlpatterns = [
path("january", views.index),
]
This creates a URL pattern that maps the "january" path to our index
view.
3. Include App URLs in Project URLs
Finally, we need to make the project aware of our app's URLs. Open the urls.py
file in your project's main directory and update it like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("challenges/", include("challenges.urls")),
]
This includes the URLs from our 'challenges' app under the "challenges/" path.
Now, when you run your server and navigate to http://localhost:8000/challenges/january, you should see the message "Hello, this is the January challenge!".
Understanding the Flow:
- User visits http://localhost:8000/challenges/january
- Django checks the main
urls.py
and sees that "challenges/" should use the URLs from the challenges app - It then checks the app's
urls.py
and finds the "january" pattern - This pattern points to the
index
view inviews.py
- The view returns an HttpResponse, which Django sends back to the user's browser
This is a basic example, but it demonstrates the fundamental flow of URLs and views in Django.
Related Web Basics Articles:
- Understanding HTTP Methods: GET, POST, PUT, DELETE
- Working with Django Templates
- Django Models and Database Interactions
- Django Forms: Handling User Input
- Django's Request and Response Objects in Depth
These related articles will help you build a more comprehensive understanding of web development with Django. Each topic expands on the concepts introduced here and will help you create more complex and feature-rich applications.
- Details
- Written by: Vim
- Parent Category: Learning
- Category: Learning Django Python Framework
- Hits: 96
Django Basic Commands For Setting Up A Site
Setup Command: django-admin startproject <myproject>
During setup, the root level of your project will be called whatever you've named it in this command. There will be another sub-directory with the same name which is what Django calls an "application" which are essentially "modules"
[vim@localhost dev]$ django-admin startproject mysite
[vim@localhost dev]$ tree .
.
└── mysite <------- This is your project directory
├── manage.py <------- This is a command-line utility to interact with Django
└── mysite <------- This sub-directory is an automatically created "application"
├── asgi.py
├── __init__.py <------- This is for python so python knows this dir is a python module
├── settings.py
├── urls.py
└── wsgi.py
2 directories, 6 files
manage.py This is a command-line utility that lets you interact with your Django project. You can use it to start a development server, create applications, and perform various administrative tasks.
asgi.py This file is an entry-point for ASGI-compatible web servers to serve your project. ASGI stands for Asynchronous Server Gateway Interface and is designed for handling asynchronous web requests.
__init__.py This file makes the directory it's in a Python package. It can be empty or contain initialization code for the package.
settings.py This file contains all the configuration settings for your Django project. It includes database configuration, installed applications, middleware, template settings, and more.
urls.py This file defines the URL routing for your project. It maps URL patterns to views, so when a user requests a specific URL, Django knows which view to execute.
wsgi.py This file is an entry-point for WSGI-compatible web servers to serve your project. WSGI stands for Web Server Gateway Interface and is the standard for Python web application development.
python manage.py startapp <appname>
[vim@localhost mysite]$ python manage.py startapp challenges
[vim@localhost mysite]$ tree .
.
├── challenges <------- This is another app we've just created
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── mysite
├── asgi.py
├── __init__.py
...
python manage.py runserver
Troubleshooting:
django-admin will be setup up on installation in /usr/local/bin/ this will not be able to be found by bash nor python path while as root. Do not run this command as root!
Understanding URIs, URLs, Routes, And Views
Please DO NOT SKIP, understanding the nuances of how web request, responses are done is crucial
Routes are how Django creates and manages the pathing part of a URL: scheme://user:password@host:port/path When running the django builtin development server it will also manage the port and listening addresses. However in production the port and listening addresses is managed by the web daemon (http, nginx). Note a listening address is a list/range of IPs that a web daemon will accept requests from i.e. setting the listening address to 127.0.0.1 will only listen for requests from the same machine; setting to 0.0.0.0 will listen and accept requests from any IP.
Views are the actions; the logic that is executed for different URLs and HTTP methods.
Views in Django in its' most basic form is a python function/class which is executed automatically when a request for a certain URL is made and reaches the Django server.
More specifically views are responsible for: loading and preparing data, run any other logic (like encrypting passwords), preparing and returning response data (e.g. HTML)
NOTE: Not every URL triggers a view, some URLs that point to a resource like an image or CSS file do not trigger a view and the web server daemon just returns that file. The action is returning the file.
- Details
- Written by: Vim
- Parent Category: Learning
- Category: Learning Django Python Framework
- Hits: 125