Introduction to Django 3
Hey guys! Let's dive into the wonderful world of Django 3. Django, a high-level Python web framework, is designed to encourage rapid development and clean, pragmatic design. Django 3, in particular, brings some awesome improvements and features that make web development even smoother and more efficient. If you're new to Django, don't worry! We'll take it step by step.
So, what makes Django so special? Well, it follows the Model-View-Template (MVT) architectural pattern, which helps you keep your code organized and maintainable. Think of it as having separate compartments for your data (Models), your logic (Views), and your presentation (Templates). This separation of concerns makes it easier to work on different parts of your application without messing everything else up.
One of the key advantages of using Django is its "batteries-included" philosophy. This means that Django comes with a ton of built-in features that you would otherwise have to build yourself or install separately. Things like an ORM (Object-Relational Mapper), which lets you interact with your database using Python code, a powerful templating engine, and a robust admin interface are all included right out of the box. This can save you a lot of time and effort, especially when you're just starting out.
Django 3 also includes significant improvements in terms of asynchronous support. With async and await, you can write non-blocking code that can handle multiple requests concurrently. This is particularly useful for applications that need to handle a lot of I/O-bound operations, such as making external API calls or reading from a database. Asynchronous views and middleware can greatly improve the performance and scalability of your Django applications.
Another great feature of Django is its security. Django takes security very seriously and provides built-in protection against common web vulnerabilities like Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and SQL injection. By using Django's built-in security features, you can greatly reduce the risk of your application being compromised.
Setting Up Your Development Environment
Before we start building anything, we need to set up our development environment. First, make sure you have Python 3.6 or higher installed on your system. You can check your Python version by opening a terminal and running python3 --version. If you don't have Python installed, you can download it from the official Python website.
Next, we need to install virtualenv, which is a tool that allows you to create isolated Python environments for your projects. This is important because it prevents different projects from interfering with each other's dependencies. You can install virtualenv using pip, the Python package installer:
pip install virtualenv
Once virtualenv is installed, you can create a new virtual environment for your project. Navigate to your project directory in the terminal and run:
virtualenv venv
This will create a new directory called venv in your project directory. To activate the virtual environment, run:
source venv/bin/activate
Now that your virtual environment is activated, you can install Django using pip:
pip install Django==3.2
We're using Django 3.2 here because it's a Long-Term Support (LTS) version, which means it will receive security updates and bug fixes for a longer period of time. Once Django is installed, you can verify the installation by running:
django-admin --version
This should print the version of Django that you have installed. If everything looks good, you're ready to start building your first Django project!
Creating Your First Django Project
Alright, let's get our hands dirty and create a new Django project. Open your terminal, navigate to the directory where you want to create your project, and run the following command:
django-admin startproject myproject
This will create a new directory called myproject containing the basic structure of a Django project. Let's take a look at what's inside:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
manage.py: A command-line utility for running administrative tasks, such as starting the development server, running tests, and creating database migrations.myproject/: The main package directory for your project.__init__.py: An empty file that tells Python that this directory should be considered a Python package.settings.py: Contains the settings for your Django project, such as database configuration, installed apps, and middleware.urls.py: Defines the URL patterns for your project.asgi.py: An entry-point for ASGI-compatible web servers to serve your project.wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.
Now, let's start the development server to make sure everything is working correctly. Navigate to the myproject directory and run:
python manage.py runserver
This will start the development server on http://127.0.0.1:8000/. Open your web browser and go to that address. You should see the default Django "It worked!" page. If you see this page, congratulations! You've successfully created your first Django project.
Creating Your First App
In Django, a project is a collection of apps. An app is a self-contained module that implements a specific feature of your website. For example, you might have an app for handling user authentication, an app for managing blog posts, or an app for processing payments.
To create a new app, run the following command:
python manage.py startapp myapp
This will create a new directory called myapp containing the basic structure of a Django app. Let's take a look at what's inside:
myapp/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
__init__.py: An empty file that tells Python that this directory should be considered a Python package.admin.py: Contains the configuration for the Django admin interface.apps.py: Contains the configuration for the app.migrations/: Contains database migrations for the app.__init__.py: An empty file that tells Python that this directory should be considered a Python package.
models.py: Defines the data models for the app.tests.py: Contains unit tests for the app.views.py: Defines the views for the app.
Before we can use our new app, we need to add it to the INSTALLED_APPS setting in myproject/settings.py. Open myproject/settings.py and add 'myapp' to the INSTALLED_APPS list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # Add this line
]
Now that our app is installed, we can start defining our data models, views, and templates.
Defining Models
Models are Python classes that define the structure of your data. Each model represents a table in your database, and each field in the model represents a column in the table. Django uses an ORM (Object-Relational Mapper) to map your models to database tables, so you don't have to write any SQL code.
Let's define a simple model for storing blog posts. Open myapp/models.py and add the following code:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
This defines a Post model with four fields:
title: A character field for storing the title of the blog post.content: A text field for storing the content of the blog post.created_at: A date and time field that automatically sets the current date and time when the post is created.updated_at: A date and time field that automatically updates the current date and time when the post is updated.
The __str__ method defines how the model should be represented as a string. In this case, we're returning the title of the post.
Migrating the Database
Whenever you make changes to your models, you need to create and apply a migration to update your database schema. To create a migration, run the following command:
python manage.py makemigrations
This will create a new migration file in the myapp/migrations directory. To apply the migration, run:
python manage.py migrate
This will update your database schema to match your models. Now, you can start interacting with your models using the Django ORM.
Creating Views
Views are Python functions that handle HTTP requests and return HTTP responses. A view can render a template, redirect to another page, or return JSON data.
Let's create a simple view that displays a list of blog posts. Open myapp/views.py and add the following code:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'myapp/post_list.html', {'posts': posts})
This defines a post_list view that retrieves all blog posts from the database and renders them using the myapp/post_list.html template. The render function takes the request object, the template name, and a dictionary of context variables as arguments. The context variables are passed to the template, where they can be used to generate the HTML output.
Defining URLs
To make our view accessible, we need to define a URL pattern that maps a URL to the view. Create a new file called myapp/urls.py and add the following code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]
This defines a URL pattern that maps the root URL (/) to the post_list view. The name argument is used to give the URL pattern a name, which can be used to generate URLs in templates and views.
Now, we need to include our app's URLs in the project's URLs. Open myproject/urls.py and add the following code:
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
This includes the URLs defined in myapp/urls.py under the root URL (/). Now, when you go to http://127.0.0.1:8000/, Django will use the post_list view to handle the request.
Creating Templates
Templates are HTML files that define the structure and content of your web pages. Django uses a powerful templating engine that allows you to dynamically generate HTML output using context variables.
Let's create a template for displaying the list of blog posts. Create a new directory called myapp/templates and create a new file called myapp/templates/myapp/post_list.html with the following code:
<!DOCTYPE html>
<html>
<head>
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li><a href="#">{{ post.title }}</a></li>
{% endfor %}
</ul>
</body>
</html>
This template displays a list of blog posts. The {% for %} tag iterates over the posts context variable, and the {{ post.title }} tag displays the title of each post.
Now, when you go to http://127.0.0.1:8000/, you should see a list of blog posts. If you don't have any blog posts in your database, you'll need to create some using the Django admin interface or the Django ORM.
Django Admin Interface
Django comes with a built-in admin interface that allows you to easily manage your data. To access the admin interface, go to http://127.0.0.1:8000/admin/. You'll be prompted to enter a username and password. If you don't have a superuser account, you'll need to create one using the createsuperuser command:
python manage.py createsuperuser
Enter your desired username, email address, and password. Once you've created a superuser account, you can log in to the admin interface.
Registering Your Models
To make your models available in the admin interface, you need to register them in myapp/admin.py. Open myapp/admin.py and add the following code:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
This registers the Post model with the admin interface. Now, when you go to http://127.0.0.1:8000/admin/, you should see a Posts section in the Myapp app. You can click on Posts to view, add, edit, and delete blog posts.
Conclusion
In this cookbook, we've covered the basics of Django 3 web development. We've learned how to set up a development environment, create a new Django project, create a new app, define models, create views, define URLs, create templates, and use the Django admin interface.
With these basic concepts in hand, you can start building your own web applications using Django 3. Good luck, and have fun!
Lastest News
-
-
Related News
1974 Champions League Final: Why The Replay?
Alex Braham - Nov 9, 2025 44 Views -
Related News
Funeral Homes In Melbourne, FL: Guide
Alex Braham - Nov 13, 2025 37 Views -
Related News
Masa Depan Gamer Indonesia: Apa Yang Menanti?
Alex Braham - Nov 17, 2025 45 Views -
Related News
Project Evo: Download & Install Guide From Play Store
Alex Braham - Nov 12, 2025 53 Views -
Related News
OSC International Finance Bureau: What You Need To Know
Alex Braham - Nov 13, 2025 55 Views