Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Django Tutorial in Python

Django Tutorial in Python

? Django Tutorial in Python

Django is a high-level web framework for Python that enables rapid development of web applications. It follows the Model-View-Template (MVT) architectural pattern, similar to the Model-View-Controller (MVC) pattern. Django takes care of a lot of the hassle of web development by providing built-in tools and features for database management, URL routing, user authentication, and more.

Here's a step-by-step guide to get started with Django:


? 1. Setting Up a Django Project

Step 1: Install Django

To begin using Django, you need to install it using pip (Python's package manager).

pip install django

Step 2: Create a Django Project

Once Django is installed, create a new Django project by running the following command:

django-admin startproject myproject

This will create a directory called myproject with the following structure:

myproject/    manage.py    myproject/        __init__.py        settings.py        urls.py        wsgi.py
  • manage.py: A command-line utility that helps with various administrative tasks like running the server, migrating databases, and more.

  • settings.py: Contains settings and configurations for your project (e.g., database setup, installed apps, etc.).

  • urls.py: Contains URL routing for your project.

  • wsgi.py: A file for deploying the project to a web server.

Step 3: Run the Development Server

Navigate into your project directory and run the development server to test if everything works.

cd myprojectpython manage.py runserver

Open a browser and visit http://127.0.0.1:8000/ — you should see the Django welcome page!


? 2. Creating a Django App

In Django, an app is a web application that does something (e.g., a blog, a shop, etc.). You can have multiple apps in one project.

Step 1: Create an App

Create a new app inside your project using the following command:

python manage.py startapp myapp

This will create a new directory myapp/ with the following structure:

myapp/    migrations/    __init__.py    admin.py    apps.py    models.py    views.py    tests.py    urls.py
  • models.py: Defines the database models (tables).

  • views.py: Contains the logic for handling requests and returning responses.

  • urls.py: Contains the URL routing for this app.

  • admin.py: Registers models to be managed through Django’s admin panel.

Step 2: Register the App in settings.py

Open myproject/settings.py and add your app to the INSTALLED_APPS list.

INSTALLED_APPS = [    'myapp',  # Add the app here    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]

? 3. Creating Models

In models.py, you define the structure of your database tables by creating classes that inherit from django.db.models.Model.

Example: Creating a Post model for a blog

from django.db import modelsclass Post(models.Model):    title = models.CharField(max_length=100)    content = models.TextField()    created_at = models.DateTimeField(auto_now_add=True)    def __str__(self):        return self.title

Step 1: Migrate the Database

To create the database table for this model, you need to run the following commands:

python manage.py makemigrationspython manage.py migrate
  • makemigrations: Creates migration files based on your model changes.

  • migrate: Applies the migrations to the database.


? 4. Creating Views

In views.py, you define functions (or class-based views) that take HTTP requests and return HTTP responses.

Example: Creating a simple view

from django.shortcuts import renderfrom .models import Postdef home(request):    posts = Post.objects.all()  # Retrieve all posts from the database    return render(request, 'home.html', {'posts': posts})

Here:

  • Post.objects.all() retrieves all the posts from the database.

  • render() renders an HTML template with the context (data).


? 5. Creating URLs

In urls.py, you map URLs to views. First, create a urls.py file inside your app directory (if it doesn't already exist), and then link it to the main urls.py of the project.

Example: Defining URL patterns for the app

from django.urls import pathfrom . import viewsurlpatterns = [    path('', views.home, name='home'),]

Step 1: Include App URLs in Project URLs

Now, open the project's urls.py (in myproject/urls.py) and include the app's URLs:

from django.contrib import adminfrom django.urls import path, includeurlpatterns = [    path('admin/', admin.site.urls),    path('', include('myapp.urls')),  # Include the app URLs]

? 6. Creating Templates

Django uses HTML templates for rendering dynamic content. Templates are typically stored in a templates/ directory within the app.

Step 1: Create a Template Directory

Inside your app directory, create a folder called templates and then another folder with the same name as your app (e.g., myapp).

myapp/    templates/        myapp/            home.html

Step 2: Create the home.html Template

In home.html, you can display dynamic content:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Blog</title></head><body>    <h1>Blog Posts</h1>    <ul>        {% for post in posts %}            <li>{{ post.title }} - {{ post.created_at }}</li>        {% endfor %}    </ul></body></html>
  • {% for post in posts %}: A template tag that loops through the list of posts.

  • {{ post.title }}: A template variable that inserts the post's title.


? 7. Using the Django Admin Interface

Django provides an admin interface that allows you to manage models through a web interface.

Step 1: Register Models in admin.py

In admin.py, register the models that you want to manage through the admin panel:

from django.contrib import adminfrom .models import Postadmin.site.register(Post)

Step 2: Create a Superuser

To access the admin interface, you need to create a superuser:

python manage.py createsuperuser

Follow the prompts to create a user.

Step 3: Access the Admin Panel

Run the server:

python manage.py runserver

Now, visit http://127.0.0.1:8000/admin/ in your browser and log in with the superuser credentials.


? 8. Conclusion

This is a basic introduction to Django. The framework provides much more functionality, such as handling forms, user authentication, and deploying applications to production servers.

  • Models define your data.

  • Views handle the logic and return responses.

  • Templates allow you to create dynamic HTML pages.

  • Admin Panel helps in managing the database via a web interface.

For more advanced features and functionality, you can explore the official Django documentation: Django Documentation.

Let me know if you need further examples or assistance! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql