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
Top comments (0)