Django part: 1

Photo by Faisal on Unsplash

Django part: 1

Starting with just short introduction of what is Django and framework is :

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.One of Django's key strengths is its built-in features, which facilitate various aspects of web development, including URL routing, template engine, object-relational mapping (ORM)

A framework is a pre-built structure or platform that provides a foundation for building software applications. It typically includes libraries, tools, and predefined conventions to streamline the development process.

Install Django

Install Django using pip:

pip install django

Creating a New Project in Django

Step 1: Create a new Django project

django-admin startproject myproject

This command will create a new directory named "myproject" containing the necessary files and directories for your Django project.

Step 2: Run the development server

python manage.py runserver

This command will start the development server, and you should see output indicating that the server is running. By default, the server will be accessible at http://127.0.0.1:8000/ in your web browser.

Creating Folders for Django Application

  1. Templates folder: This folder is used to store HTML templates for your Django application's views.

  2. Static folder: This folder is used to store static assets such as CSS, JavaScript, images, and other files that are served directly to the client's browser.

  3. Media folder: This folder is used to store media files uploaded by users, such as images, videos, and documents

mkdir templates static media

Add the templates directory to your Django project's settings

  1. Open your Django project's settings.py file in a text editor.
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))

TEMPLATES = [ { ...

'DIRS': [os.path.join(BASE_DIR, 'templates')],

... }, ]

By adding the templates directory to the 'DIRS' option in the TEMPLATES setting, Django will now search for template files in the specified directory when rendering views.

What is default migration How to Migrate Default Migration in Django

In Django, a default migration refers to an initial migration that is automatically created when you create a new app using the django-admin startapp command or by using the manage.py startapp command. This migration file typically contains the initial database schema for the models defined within the app.

1 . Create the default migration: If you've created models in your Django app, you'll need to generate an initial migration that defines the database schema based on those models.

python manage.py makemigrations
  1. Apply the migration:

     python manage.py migrate
    

Install Database Browser for SQLite in Windows

  1. Download the installer:

    https://sqlitebrowser.org/dl/ download the appropriate installer for Windows.

What is Superuser in Django and How to Create it

In Django, a superuser is a user account with special privileges that enable them to perform administrative tasks within the Django admin interface. Superusers have full access to all functionalities provided by the Django admin, allowing them to manage users, groups, permissions, and other administrative tasks.

  1. Navigate to your Django project directory

  2. Activate the virtual environment (if applicable):

    source <venv_name>/bin/activate # Replace <venv_name> with the name of your virtual environment

  3. Run the createsuperuser command:

     python manage.py createsuperuser
    
  4. Enter the required information: You'll be prompted to enter the following information for the superuser account:

    • Username: Choose a username for the superuser.

    • Email address: Provide an email address for the superuser.

    • Password: Set a password for the superuser. Note that the password won't be displayed on the screen for security reasons. Type the password and press Enter.

Use URLs & Views in Django

Using URLs and views in Django is fundamental for defining the structure of your web application and specifying the logic to execute when a particular URL is accessed.

1. Define URL patterns:

in the urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('about/', views.about, name='about'),
    # Add more URL patterns as needed
]

2. Create views:

Example views in views.py:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Welcome to the homepage!")

def about(request):
    return HttpResponse("This is the about page.")
  1. Include application URLs in project URLs:

    Finally, include the URLs of your application in the project's main urls.py file using the include() function. This function allows you to delegate URL routing to specific applications.

    Example urls.py in the project directory:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Creating a Dynamic URL in Django

Creating a dynamic URL in Django involves defining URL patterns that include parameters, which are then captured and passed to view functions for further processing.

  1. Define URL pattern:

    In your urls.py file, define a URL pattern that includes placeholders for integer, string, and slug parameters using angle brackets <int:>, <str:>, <slug:>. These placeholders will capture the values passed in the URL and pass them to the corresponding view function.

     from django.urls import path
     from . import views
    
     urlpatterns = [
         path('profile/<int:user_id>/', views.profile_by_id, name='profile_by_id'),
         path('profile/<str:username>/', views.profile_by_username, name='profile_by_username'),
         path('article/<slug:slug>/', views.article_detail, name='article_detail'),
         # Add more URL patterns as needed
     ]
    
  2. Create view functions:

     from django.shortcuts import render, HttpResponse
    
     def profile_by_id(request, user_id):
         return HttpResponse(f"Profile Page for user ID: {user_id}")
    
     def profile_by_username(request, username):
         return HttpResponse(f"Profile Page for username: {username}")
    
     def article_detail(request, slug):
         return HttpResponse(f"Article Detail Page for slug: {slug}")
    

Render an HTML Template as Response

  1. Create an HTML template:

    First, create an HTML template file that contains the desired HTML structure and content. You can create this file in the templates directory of your Django app.

    For example, let's say you have a template named example.html:

     <!-- example.html -->
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Example Page</title>
     </head>
     <body>
         <h1>Hello, world!</h1>
         <p>This is an example page.</p>
     </body>
     </html>
    
  2. Create a view function: Define a view function in your views.py file that loads and renders the HTML template.

     from django.shortcuts import render
    
     def example_view(request):
         return render(request, 'example.html')
    
  3. Map the URL to the view function: Define a URL pattern in your urls.py file that maps to the view function you created.

     from django.urls import path
     from . import views
    
     urlpatterns = [
         path('example/', views.example_view, name='example'),
         # Other URL patterns...
     ]