


A Beginner's Guide to Django Web Framework: Creating Apps, Views, Configuring URLs and Templates
Building Web Applications with Django ,A Practical Guide.?️ ???
Capsule 2: Creating Apps ,Views, templates and configuring route
Greetings comrades Welcome back to our Django tutorial series! it’s another week and we need to take our KodeCapsule of the week. In the previous article we, covered the foundations of Django framework, it’s architecture, Models, Views, templates and how to start a new project in Django. If you have not read the last article I suggest you go back and read that article, here before continuing. So, grab a cap of coffee and let’s dive in.
Outline of Article
Introduction
What is an app in Django?
Creating an App in Django
Creating Views for your App
Creating URLs for your app
Adding templates to your app
Conclusion
References
Introduction
In this tutorial we will dive deep into building and working with the core components of any Django project. We will look at how to create apps in Django, configuring settings, creating views to handle request and setting up URL routes. By the end of this tutorial, you should understand
How to create a new app in Django
How to include this app in your project’s settings
How to define URL patterns for your app
How to write views to display request and response
How to add templates to your app
Let’s Get Started!!!!!!!
What is an App in Django?
An app in django is a module that performs a specific function. An app can be as simple as a feature in your project like a contact form or a fully-fledged component such as a blog or a payment system. Apps are designed to be reusable across different projects. Organizing your code into apps enable code reusability, maintainability and scalability. The difference between an app and a project is that, an app does a specific function in your project and can be used in multiple projects but a project consists of a collection of configurations, apps for a particular website. Some key characteristics of an app are:
Modularity: Django Apps are modular in nature which means that you can develop and test your apps independently and reuse them. This makes your project more organized and manageable.
Reusability: Since apps are self-contained, you can easily reuse them in other Django projects. For example, you can create a blog app for one project and use the same app in another project without modifications.
Separation of Concerns: Each app handles a specific aspect of your project. This separation makes it easier to manage different parts of your application.
Encapsulation: Apps encapsulate models, views, templates, static files, and other components related to a specific functionality, keeping them organized within their own directories.
Creating an App in Django
In the previous article we have already setup our project. We will create our first app. This app is going to be a blog application.
1.To create the app, navigate into your project folder and in your terminal and run this command. Make sure you have activated your virtual environment.
python manage.py startapp blog
This command creates a new directory with all the necessary setup files in a folder structure described below:
├── blog/
│ ├── migrations/
│ │ └──init.py
│ ├── init.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
I. migrations/: This folder stores all the database migrations for your app
II. init.py: This is an empty file that informs python to treat that directory as a python package.
III. admin.py: A configuration files for django admin interface. The function of admin.py file is to register your apps models in the django admin panel. We will look at Django admin later
IV. apps.py: This contains configurations for the app and can include the app’s metadata as well.
V. models.py: This script is where we fine the data models for our app.
VI. tests.py: The test.py script is where you write test cases for your app
VII. views.py: This script contains the views you define for your app. The views handle the business logic for your application.
2.Add your blog app into the list of installed apps in the project settings.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps 'blog', ]
Creating Views
Views play an important role in your application. The business logic for your application is defined in Views. Views act as the glue between the presentation layer and the data layer. There are two main types of views in Django, Function-based views and Class-based views (more details about this in the upcoming articles). In this tutorial we will stick to using function-based views.
1.Open the views.py file in your blog app
2.Import HttpResponse from the http package
from django.http import HttpResponse
3.Define a function called home (you can name the function whatever you want). The function will return an HttpResponse
from django.http import HttpResponse def home(request): return HttpResponse("<h1>Welcome to the Home Page</h1>")
Creating URLs for your App
For users to access different sections of your web app, you have to define access points for each feature/functionality of your app; in Django you do so by creating urls for your app. URLs patterns are mapped to specific views.
In Django, you can define all the urls for your project in the project urls.py script, but it is best practice to create a separate urls.py script for individual apps in your project.
1.In the blog app directory create a urls.py script.
2.Import the path function from the urls package in django. The path function takes three arguments, route, view, kwargs and name and returns an element. You can read more about this function here.
from django.urls import path
3.Import the views for your app
from . import views
4.Create a list called urlpatterns an define a url for the home page, this list is similar to the list in the project urlpatterns.
urlpatterns = [ path('', views.home, name='home_page' ]
5.Update the project’s urls. To make your app accessible you need to update the main project urls.py . Open your project’s urls.py file and import the include function from urls package and update the urlpatterns list.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ]
6.After that save all your files and start the development server, using the usual command
python manage.py runserver
Open the url in your browser and the default django home page changes the response from the home function.
Adding templates to your App
In the previous section the repose from the home view return an http response that contains an HTML header tag. What if we want to return a whole page that contains a whole lot of HTML tags, what can we do? That’s where templates in django come in. Django templates allows you to define the HTML structure that will be displayed in the user's browser. Templates allow you to generate dynamic content using the Django Templating Language (DTL). In Django you put your templates in your app or at the root of your application( more details about django templates in my upcoming articles).
1.Create a template directory: create a template directory in your blog app. In the template directory create another directory called blog.
2.Create a template. Create and HTML file called
myproject/ blog/ templates/ blog/ index.html
3.Update the index.html file with this code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Blog App</title> </head> <body> <h1>Welcome to the Home page</h1> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptas maiores, modi facilis veritatis amet eum labore odio sit nemo eius?</p> </body> </html>
4.Update the home view: Open your views file and import render from shortcuts. Update the function body to return the index.html using the render function.
from django.shortcuts import render def home(request): return render(request, 'blog/index.html')
Save the changes and reload your browser.
Conclusion
We have come to the end of this week’s Kodecapsule . In this article we looked at creating your first app in django, creating views, configuring urls and rendering templates in django. In the next article we will take a look at models and templates into details.
Be sure to watch out for the articles in this series as I take you from Zero to an expert in Django.
Your Suggestions and Comments are always welcome.
Kuseh Wewoliamo
References
https://docs.djangoproject.com/en/5.0/topics/http/views/
https://docs.djangoproject.com/en/5.0/topics/templates/
https://docs.djangoproject.com/en/5.0/ref/urls/#include
https://docs.djangoproject.com/en/5.0/ref/urls/#path
https://www.w3schools.com/django/django_create_app.php
The above is the detailed content of A Beginner's Guide to Django Web Framework: Creating Apps, Views, Configuring URLs and Templates. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
