#38 -Django Basics

#38 -Django Basics

By Ifeanyi Omeata


Topics:


VIDEO TUTORIALS


V1. Full-Featured Web App Part 1 - Getting Started
V2. Full-Featured Web App Part 2 - Applications and Routes
V3. Full-Featured Web App Part 3 - Templates
V4. Full-Featured Web App Part 4 - Admin Page
V5. Full-Featured Web App Part 5 - Database and Migrations
V6. Full-Featured Web App Part 6 - User Registration
V7. Full-Featured Web App Part 7 - Login and Logout System
V8. Full-Featured Web App Part 8 - User Profile and Picture
V9. Full-Featured Web App Part 9 - Update User Profile
V10. Full-Featured Web App Part 10 - Create, Update, and Delete Posts
V11. Full-Featured Web App Part 11 - Pagination
V12. Full-Featured Web App Part 12 - Email and Password Reset
V13. Deploying Your Application (Option #1) Part 13 - Deploy to a Linux Server
V14. How to Use a Custom Domain Name for Our Application Part 14
V15. How to enable HTTPS with a free SSL/TLS Certificate using Let's Encrypt Part 15
V16. Using AWS S3 for File Uploads Part 16
V17. Deploying Your Application (Option #2) Part 17 - Deploy using Heroku
V18. Django Hotel Management System [ HMS ] Part 1 - Room Model #1
V19. Django Hotel Management System [ HMS ] Part 2 - Room Availability Logic #2
V20. Django Hotel Management System [HMS] Part 3 - Booking Form & Logic #3
V21. Django Hotel Management System [HMS] Part 4 - Adding HTML Templates #1
V22. Django Hotel Management System [HMS] Part 5 - Adding HTML Templates #2
V23. Django Hotel Management System [HMS] Part 6 - Authentication using django-allauth
V24. Django Hotel Management System [HMS] Part 7 - Booking List HTML & Booking Cancellation
V25. Django Hotel Management System [HMS] Part 8 - Views Code Refactor
V26. Django Hotel Management System [HMS] Part 9 - Environment Variables in Python/Django
V27. Django Multiuser Registration and Login based on Role
V28. How to Create a Login System in Python Using Django
V29. Get started with Django - models & Admin site Part 1
V30. Django Views, URLs and Templates Part 2
V31. Django Forms & Model Forms Part 3
V32. Django Update & Delete Views Part 4
V33. Django Basic CRUD app Code Refactoring Part 5
V34. Django Class Based Views Tutorial Part 6
V35. Django User Profile with Django Signals Part 7
V36. Django User Profile with Django Signals Part 8
V37. Django Model Managers | Advanced Django ORM Part 9
V38. Django Tutorial for Beginners | Full Course
V39. Django For Beginners - Full Tutorial
V40. Python Django Tutorial for Beginners
V41. Pipenv - Easily Manage Packages and Virtual Environments
V42. Pipenv Crash Course by Traversy Media
V43. Getting Started With Django REST Framework
V44. Django REST Framework Oversimplified
V45. Django Rest Framework - Serializers & CRUD
V46. Todo App | Django REST Framework & Ajax
V47. Email OTP verification Django Rest Framework
V48. Login with OTP Django
V49. Django Authentication Basics
V50. Django Tutorials
V51. Passing Values Through the URL in Django
V52. Django Projects
V53. Django Customer Management App
V54. CI/CD Tutorials
V55. Try Django 3.2 - Python Web Development Tutorial Series
V56. Git & Github Crash Course for all Developers
V57. The Basics of Django ListView


Setup Environment

1. Install VENV
2. Create Requirements
3. Install Django
4. View Django version
5. Create Django Project


BLOG APP - Home

6. Create blog App
7. Run Django Server
8. Register blog app to INSTALLED_APPS
9. Add App URL path to Project URLS
10. Create App URLS file
11. Create views with HttpResponse
12. Create HTML files in Templates Folder
13. Use render to view HTML files
14. Post dynamic contents from views.py to HTML files
15. View dynamic contents in HTML files
16. Create Base HTML file for Templating
17. Set HTML files to extend from Base Template
18. Load Static CSS file to Base HTML Template
19. Set URL links to Menus
20. Configure Bootstrap5 for Templates
21. Setup and Create Admin tables with migration
22. Create Super User for Admin access
23. Admin Login with Superuser credentials
24. Create Model for Post table
25. Create Migration for Post table Model
26. View SQL Migration Statements for Post table Model
27. Run Migration to create Post table
28. Run Python Shell Queries
29. Make Post Objects more descriptive
30. Read Posts from Database
31. Format the Post Date
32. Register Post Model with Admin Panel
33. Add new Posts with Admin Panel


USERS APP - Register

34. Create Users App in Project
35. Register Users App in Project Settings
36. Link App URL to Project URL
37. Create App URL
38. Create register View with UserCreationForm
39. Create Template file for register.html page
40. Format register.html Form with "as_p"
41. Refactor View to save UserCreationForm entries
42. Refactor View to add Email Field
43. Install Crispy Forms to Style Template
44. Register Crispy Forms in Project settings
45. Load Crispy Forms in Register page


USERS APP - Login and Logout

46. Setup Project URL for Users URLs
47. Setup Login and Logout URLs with Class-based Views
48. Create Login page in Templates
49. Set Login redirect URL in Settings
50. Refactor View.Register to Redirect to Login Page
51. Create Logout Template
52. Refactor base.html menu to show Logout option


USERS APP - Profile page

53. Create View for Profile page
54. Create HTML Template for Profile page
55. Create URL route for profile page
56. Set Profile menu in base.html
57. Force User to be logged in before Access
58. Create Profile Model
59. Install Pillow for Profile model Migration
60. Run Profile model Migration


POLLS APP

0-1. Using PULL_REQUEST_TEMPLATE.md
0-2. Using GitHub Actions
0-3. Creating App project
0-4. Starting Development Server
0-5. Creating the Polls app
0-6. Write your first view
0-7. Map your view to App URL
0-8. Include App URL in Base (Project) URL List
0-9. Deploying Migrations (set default db)
0-10. Include App URL in Base (Project) URL List


IMPORTANT CODE

1-1. Basics
1-2. List View
1-3. DateTimeField Widget


DJANGO REST FRAMEWORK (DRF)

2-1. PIPENV
2-2. Create Django Project
2-3. Create Django app
2-4. Run Migrations
2-5. Create Superuser
2-6. Install Django Rest Framework
2-7. Add Rest_framework and apps to settings.py
2-8. Set Project URLs
2-9. Create Model
2-10. Register Model in Admin
2-11. Run server



VIDEO TUTORIALS


V1. Full-Featured Web App Part 1 - Getting Started


>>Return to Menu


V2. Full-Featured Web App Part 2 - Applications and Routes


>>Return to Menu


V3. Full-Featured Web App Part 3 - Templates


>>Return to Menu


V4. Full-Featured Web App Part 4 - Admin Page


>>Return to Menu


V5. Full-Featured Web App Part 5 - Database and Migrations


>>Return to Menu


V6. Full-Featured Web App Part 6 - User Registration


>>Return to Menu


V7. Full-Featured Web App Part 7 - Login and Logout System


>>Return to Menu


V8. Full-Featured Web App Part 8 - User Profile and Picture


>>Return to Menu


V9. Full-Featured Web App Part 9 - Update User Profile


>>Return to Menu


V10. Full-Featured Web App Part 10 - Create, Update, and Delete Posts


>>Return to Menu


V11. Full-Featured Web App Part 11 - Pagination


>>Return to Menu


V12. Full-Featured Web App Part 12 - Email and Password Reset


>>Return to Menu


V13. Deploying Your Application (Option #1) - Deploy to a Linux Server


>>Return to Menu


V14. How to Use a Custom Domain Name for Our Application


>>Return to Menu


V15. How to enable HTTPS with a free SSL/TLS Certificate using Let's Encrypt


>>Return to Menu


V16. Using AWS S3 for File Uploads


>>Return to Menu


V17. Deploying Your Application (Option #2) - Deploy using Heroku


>>Return to Menu


V18. Django Hotel Management System [ HMS ] Room Model #1


>>Return to Menu


V19. Django Hotel Management System [ HMS ] Room Availability Logic #2


>>Return to Menu


V20. Django Hotel Management System [HMS] Booking Form & Logic #3


>>Return to Menu


V21. Django Hotel Management System [HMS] Adding HTML Templates #1


>>Return to Menu


V22. Django Hotel Management System [HMS] Adding HTML Templates #2


>>Return to Menu


V23. Django Hotel Management System [HMS] Authentication using django-allauth


>>Return to Menu


V24. Django Hotel Management System [HMS] Booking List HTML & Booking Cancellation


>>Return to Menu


V25. Django Hotel Management System [HMS] Views Code Refactor


>>Return to Menu


V26. Django Hotel Management System [HMS] Environment Variables in Python/Django


>>Return to Menu


V27. Django Multiuser Registration and Login based on Role


>>Return to Menu


V28. How to Create a Login System in Python Using Django


>>Return to Menu


V29. Get started with Django - models & Admin site


>>Return to Menu


V30. Django Views, URLs and Templates


>>Return to Menu


V31. Django Forms & Model Forms


>>Return to Menu


V32. Django Update & Delete Views


>>Return to Menu


V33. Django Basic CRUD app Code Refactoring


>>Return to Menu


V34. Django Class Based Views Tutorial


>>Return to Menu


V35. Django User Profile with Django Signals


>>Return to Menu


V36. Django User Profile with Django Signals


>>Return to Menu


V37. Django Model Managers | Advanced Django ORM


>>Return to Menu


V38. Django Tutorial for Beginners | Full Course


>>Return to Menu


V39. Django For Beginners - Full Tutorial


>>Return to Menu


V40. Python Django Tutorial for Beginners


>>Return to Menu


V41. Pipenv - Easily Manage Packages and Virtual Environments


>>Return to Menu

https://realpython.com/pipenv-guide/

https://pipenv.pypa.io/en/latest/

$ pip install --user pipenv

$ brew install pipenv


V42. Pipenv Crash Course by Traversy Media


>>Return to Menu


V43. Getting Started With Django REST Framework


>>Return to Menu


V44. Django REST Framework Oversimplified


>>Return to Menu


V45. Django Rest Framework - Serializers & CRUD


>>Return to Menu


V46. Todo App | Django REST Framework & Ajax


>>Return to Menu


V47. Email OTP verification Django Rest Framework


>>Return to Menu


V48. Login with OTP Django


>>Return to Menu


V49. Django Authentication Basics


>>Return to Menu


V50. Django Tutorials


>>Return to Menu


V51. Passing Values Through the URL in Django


>>Return to Menu


V52. Django Projects


>>Return to Menu


V53. Django Customer Management App


>>Return to Menu


V54. CI/CD Tutorials


>>Return to Menu


V55. Try Django 3.2 - Python Web Development Tutorial Series


>>Return to Menu


V56. Git & Github Crash Course for all Developers


>>Return to Menu


V57. The Basics of Django ListView


>>Return to Menu


Setup Environment


1. Install VENV


>>Return to Menu

$ python3 -m venv venv
$ source venv/bin/activate
(venv) $


2. Create Requirements


>>Return to Menu

$ pip freeze > requirements.txt
$ cat requirements.txt
numpy==1.9.2
requests==2.7.0


3. Install Django


>>Return to Menu

$ python -m pip install Django
$ django-admin


4. View Django version


>>Return to Menu

$ python -m django --version


5. Create Django Project


>>Return to Menu

$ django-admin startproject blog_project
$ ~/desktop/server/django-projects django-admin startproject blog_project


BLOG APP - Home


6. Create blog App


>>Return to Menu

$ python manage.py startapp blog


7. Run Django Server


>>Return to Menu

$ python manage.py runserver

>>>>>
Django version 3.1.5, using settings 'mypage.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


8. Register blog app to INSTALLED_APPS


>>Return to Menu

From = blog > apps.py:

from django.apps import AppConfig

class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'

Copy App Class name to = blog_project > settings.py:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog.apps.BlogConfig',
]

image.png

image.png


9. Add App URL path to Project URLS


>>Return to Menu

blog_project > urls.py:

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

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

image.png


10. Create App URLS file


>>Return to Menu

blog > urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path(' ', views.home, name='home'),
    path('about/', views.about, name='about'),
]

image.png


11. Create views with HttpResponse


>>Return to Menu

blog > views.py:

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return HttpResponse('Welcome Home!')

def about(request):
    return HttpResponse('About Page')

image.png

image.png

image.png


12. Create HTML files in Templates Folder


>>Return to Menu

blog > templates > blog > home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <h1>Blog - Home</h1>
</body>
</html>

blog > templates > blog > about.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About</title>
</head>
<body>
    <h1>About - Blog</h1>
</body>
</html>

image.png


13. Use render to view HTML files


>>Return to Menu

blog > views.py:

from django.shortcuts import render
from django.http import HttpResponse


def home(request):
    return render(request, 'blog/home.html', {})

def about(request):
    return render(request, 'blog/about.html', {})

image.png

image.png

image.png


14. Post dynamic contents from views.py to HTML files


>>Return to Menu

blog > views.py:

from django.shortcuts import render
from django.http import HttpResponse

posts = [
    {
        'author': 'John',
        'title': 'Blog Post 1',
        'description': 'Blog post 1 description',
        'date_posted': 'August 25, 2020'
    },
    {
        'author': 'Mary',
        'title': 'Blog Post 2',
        'description': 'Blog post 2 description',
        'date_posted': 'August 27, 2020'
    }
    ]

def home(request):
    return render(request, 'blog/home.html', {
        'posts': posts,
        'title': 'home'
    })

def about(request):
    return render(request, 'blog/about.html', {
        'title': 'about'
    })

image.png


15. View dynamic contents in HTML files


>>Return to Menu

blog > templates > blog > home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% if title == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{title}}</title>
    {% endif %}       
</head>
<body>
    {% for post in posts %}
        <h1>{{post.title}}</h1>
        <h2>Published on {{post.date_posted}} by {{post.author}}.</h2>
        <h2>{{ post.description }}</h2>
        <hr>
    {% endfor %}    
</body>
</html>

blog > templates > blog > about.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% if title == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{title}}</title>
    {% endif %}    
</head>
<body>
    <h1>About - Blog</h1>
</body>
</html>

image.png

image.png

image.png


16. Create Base HTML file for Templating


>>Return to Menu

blog > templates > blog > base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% if title == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{title}}</title>
    {% endif %}       
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

image.png


17. Set HTML files to extend from Base Template


>>Return to Menu

blog > templates > blog > home.html:

{% extends 'blog/base.html' %}

{% block content %}
    {% for post in posts %}
        <h1>{{post.title}}</h1>
        <h2>Published on {{post.date_posted}} by {{post.author}}.</h2>
        <h2>{{ post.description }}</h2>
        <hr>
    {% endfor %}    
{% endblock %}

blog > templates > blog > about.html:

{% extends 'blog/base.html' %}

{% block content %}
    <h1>About - Blog</h1>
{% endblock %}

image.png

image.png


18. Load Static CSS file to Base HTML Template


>>Return to Menu

blog > static > blog > main.css:

body {
    background-color: #f4f1de;
}

blog > templates > blog > base.html:

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'blog/main.css' %}">
    {% if title == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{title}}</title>
    {% endif %}       
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

image.png

image.png

image.png


19. Set URL links to Menus


>>Return to Menu

<ul class="navbar-nav me-auto mb-2 mb-md-0">
    <li class="nav-item">
        <a class="nav-link {% if title == 'home' %}active{% endif %}" aria-current="page" href="{% url 'home' %}">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link {% if title == 'about' %}active{% endif %}" href="{% url 'about' %}">About</a>
    </li>
</ul>

image.png


20. Configure Bootstrap5 for Templates


>>Return to Menu

image.png

blog > templates > blog > base.html:

{% load static %}

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'blog/main.css' %}">
    {% if title == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{title}}</title>
    {% endif %}   
</head>
<body>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="{% url 'home' %}">Weblog</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                    <a class="nav-link {% if title == 'home' %}active{% endif %}" aria-current="page" href="{% url 'home' %}">Home</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link {% if title == 'about' %}active{% endif %}" href="{% url 'about' %}">About</a>
                    </li>
                </ul>
                <ul class="navbar-nav d-flex">
                    <li class="nav-item">
                    <a class="nav-link active" aria-current="registration" href="#">Register</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link" href="#">Login</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <main class="container">
        <div class="row">
            <div class="col-md-12 col-sm-12 p-5 mb-4 bg-light rounded-3">
                <div class="container-fluid py-5">
                    <h1 class="display-5 fw-bold">{{topic}}</h1>
                    <p class="col-md-10 fs-5">{{message}}</p>
                    <button class="btn btn-success btn-lg" type="button">Register</button>
                    <button class="btn btn-danger btn-lg" type="button">Login</button>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-9 col-sm-9">
                {% block content %}{% endblock %}
            </div>    
            <div class="col-md-3 col-sm-3">
                {% block sidebar %}
                <div class="card" style="max-width: 18rem;">
                    <div class="card-header">
                        Our Sidebar
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">Contents:</li>
                        <li class="list-group-item">
                            <div class="card-header">
                                Featured
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item">Latest posts</li>
                                    <li class="list-group-item">Announcement</li>
                                    <li class="list-group-item">Calender</li>
                                </ul>
                            </div>
                        </li>
                    </ul>

                </div>
                {% endblock %}
            </div> 
        </div>
        <footer class="pt-3 pb-3 mt-4 bg-dark text-muted border-top"></footer>
    </main>   

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

blog > templates > blog > home.html:

{% extends 'blog/base.html' %}

{% block content %}
    {% for post in posts %}
        {% if forloop.counter|divisibleby:"2" %}
            <div class="row align-items-md-stretch">
                <div class="col-md-9 col-sm-9">
                    <div class="h-100 p-5 text-white bg-dark rounded-3">
                    <p>{{ post.description }}</p>
                    <button class="btn btn-outline-light" type="button">Read more...</button>
                    </div>
                </div>
                <div class="col-md-3 col-sm-3">
                    <div class="h-100 p-5 bg-light border rounded-3">
                    <h2>{{post.title}}</h2>
                    <p>By {{post.author}}</p>
                    <p>Published on {{post.date_posted}}</p>
                    </div>
                </div>
            </div> 
            <br>  
        {% endif %}
        {% if not forloop.counter|divisibleby:"2" %}  
            <div class="row align-items-md-stretch">  
                <div class="col-md-3 col-sm-3">
                    <div class="h-100 p-5 bg-light border rounded-3">
                    <h2>{{post.title}}</h2>
                    <p>By {{post.author}}</p>
                    <p>Published on {{post.date_posted}}</p>
                    </div>
                </div>
                <div class="col-md-9 col-sm-9">
                    <div class="h-100 p-5 text-white bg-dark rounded-3">
                    <p>{{ post.description }}</p>
                    <button class="btn btn-outline-light" type="button">Read more...</button>
                    </div>
                </div>
            </div> 
            <br>    
        {% endif %} 
    {% endfor %}
{% endblock %}

blog > static > blog > main.css:

@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@1,400;1,700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Raleway:wght@400;700&display=swap');

* {
    box-sizing: border-box;
}

body {
    background-color: #e5e5e5;
    height: 100vh;
    padding-top: 4.5rem;
    /* font-family: 'Playfair Display', serif; */
    font-family: 'Raleway', sans-serif;
}

.bd-placeholder-img {
    font-size: 1.125rem;
    text-anchor: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
}

@media (min-width: 768px) {
    .bd-placeholder-img-lg {
        font-size: 3.5rem;
    }
}

image.png

image.png


21. Setup and Create Admin tables with migration


>>Return to Menu

python manage.py migrate

image.png

image.png


22. Create Super User for Admin access


>>Return to Menu

python manage.py createsuperuser

image.png


23. Admin Login with Superuser credentials


>>Return to Menu

image.png

image.png

image.png


24. Create Model for Post table


>>Return to Menu

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

image.png


25. Create Migration for Post table Model


>>Return to Menu

python manage.py makemigrations

image.png


26. View SQL Migration Statements for Post table Model


>>Return to Menu

python manage.py sqlmigrate blog 0001

image.png


27. Run Migration to create Post table


>>Return to Menu

python manage.py migrate

image.png


28. Run Python Shell Queries


>>Return to Menu

python manage.py shell

Get All Users from the database:

from blog.models import Post
from django.contrib.auth.models import User

User.objects.all()
User.objects.first()

image.png

Filter User by attribute:

from blog.models import Post
from django.contrib.auth.models import User

User.objects.filter(username='peterdutch')
User.objects.filter(username='peterdutch').first()

image.png

Get User properties from user variable:

from blog.models import Post
from django.contrib.auth.models import User

user = User.objects.filter(username='peterdutch').first()
>>> user.id
>>> user.pk

image.png

Create Posts for User:

from blog.models import Post
from django.contrib.auth.models import User

user = User.objects.get(id=2)
>>> post_1 = Post(title='My first Blog', content='This is my first Post', author=user)
>>> post_2 = Post(title='My second Blog', content='This is my second Post', author=user)
>>> post_1.save()
>>> post_2.save()
>>> Post.objects.all()

image.png


29. Make Post Objects more descriptive


>>Return to Menu

blog > models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

image.png

image.png


30. Read Posts from Database


>>Return to Menu

blog > views.py:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Post

message = '''WeBlog is an online journal and informational website where 
        writers share their views on various individual subjects. Read our varied 
        acticles ranging from Politics to Religion, Sports, Entertainments, and 
        lots more! You can also register to become a writer and share your own 
        views.'''

def home(request):
    return render(request, 'blog/home.html', {
        'posts': Post.objects.all(),
        'page': 'home',
        'topic': 'Welcome to WeBlog!',
        'message': message
    })

def about(request):
    return render(request, 'blog/about.html', {
        'page': 'about',
        'topic': 'Know more about WeBlog...',
        'message': message
    })

blog > templates > blog > home.html:

{% extends 'blog/base.html' %}

{% block content %}
    {% for post in posts %}
        {% if forloop.counter|divisibleby:"2" %}
            <div class="row align-items-md-stretch">
                <div class="col-md-9 col-sm-9">
                    <div class="h-100 p-5 text-white bg-dark rounded-3">
                    <p>{{ post.content }}</p>
                    <button class="btn btn-outline-light" type="button">Read more...</button>
                    </div>
                </div>
                <div class="col-md-3 col-sm-3">
                    <div class="h-100 p-5 bg-light border rounded-3">
                    <h2>{{post.title}}</h2>
                    <p>By {{post.author}}</p>
                    <p>Published on {{post.date_posted}}</p>
                    </div>
                </div>
            </div> 
            <br>  
        {% endif %}
        {% if not forloop.counter|divisibleby:"2" %}  
            <div class="row align-items-md-stretch">  
                <div class="col-md-3 col-sm-3">
                    <div class="h-100 p-5 bg-light border rounded-3">
                    <h2>{{post.title}}</h2>
                    <p>By {{post.author}}</p>
                    <p>Published on {{post.date_posted}}</p>
                    </div>
                </div>
                <div class="col-md-9 col-sm-9">
                    <div class="h-100 p-5 text-white bg-dark rounded-3">
                    <p>{{ post.content }}</p>
                    <button class="btn btn-outline-light" type="button">Read more...</button>
                    </div>
                </div>
            </div> 
            <br>    
        {% endif %} 
    {% endfor %}
{% endblock %}

image.png

image.png


31. Format the Post Date


>>Return to Menu

<p>Published on {{post.date_posted | date:"F d, Y"}}.</p>

image.png

image.png


32. Register Post Model with Admin Panel


>>Return to Menu

blog > admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

image.png

image.png

image.png


33. Add new Posts with Admin Panel


>>Return to Menu

image.png

image.png


USERS APP - Register


34. Create Users App in Project


>>Return to Menu

python manage.py startapp users

image.png


35. Register Users App in Project Settings


>>Return to Menu

'users.apps.UsersConfig',

image.png

image.png


36. Link App URL to Project URL


>>Return to Menu

blog_project > urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
    path('register/', include('users.urls'))
]

image.png


37. Create App URL


>>Return to Menu

users > urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.register, name='register'),
]

image.png


38. Create register View with UserCreationForm


>>Return to Menu

from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm


def register(request):
    form = UserCreationForm()
    return render(request, 'users/register.html', {
        'form': form,
        'page': 'register',
    })

image.png


39. Create Template file for register.html page


>>Return to Menu

blog > templates > blog > base.html:

{% load static %}

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'blog/main.css' %}">
    {% if page == 'home' %}
        <title>Blog App</title>
    {% else %} 
        <title>Blog App - {{page | title}}</title>
    {% endif %}   
</head>
<body>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="{% url 'home' %}">Weblog</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                    <a class="nav-link {% if page == 'home' %}active{% endif %}" aria-current="page" href="{% url 'home' %}">Home</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link {% if page == 'about' %}active{% endif %}" href="{% url 'about' %}">About</a>
                    </li>
                </ul>
                <ul class="navbar-nav d-flex">
                    <li class="nav-item">
                    <a class="nav-link {% if page == 'register' %}active{% endif %}" aria-current="registration" href="{% url 'register' %}">Register</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link" href="#">Login</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <main class="container">
        <div class="row">
            {% block header %}{% endblock header %}
        </div>
        <div class="row">
            <div class="col-md-9 col-sm-9">
                {% block content %}{% endblock content %}
            </div>    
            <div class="col-md-3 col-sm-3">
                {% block sidebar %}{% endblock sidebar %}
            </div> 
        </div>
        <footer class="pt-3 pb-3 mt-4 bg-dark text-muted border-top"></footer>
    </main>   

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

users > templates > users > register.html:

{% extends 'blog/base.html' %}

{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Join Today</legend>
                {{ form }}
            </fieldset> 
            <div class="form-group">
                <button class="btn btn-success" type="submit">Sign Up</button>
            </div>   
        </form>  
        <div class="border-top pt-3">
            <small class="text-muted">
                Already Have An Account? <a class="ml-2" href="#">Sign In</a>
            </small>
        </div>  
    </div>    
{% endblock content %}

image.png

image.png


40. Format register.html Form with "as_p"


>>Return to Menu

<fieldset class="form-group">
     <legend class="border-bottom mb-4">Join Today</legend>
     {{ form.as_p }}
</fieldset>

image.png

image.png


41. Refactor View to save UserCreationForm entries"


>>Return to Menu

users > views:

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('home')
    else:
        form = UserCreationForm()

    return render(request, 'users/register.html', {
            'form': form,
            'page': 'register',
        })

image.png

blog > template > blog > base.html:

<div class="col-md-9 col-sm-9">
        {% if messages %}
             {% for message in messages %}
                  <div class="alert alert-{{ message.tags }}">
                  {{ message }}
                  </div>
             {% endfor %}
       {% endif %}
       {% block content %}{% endblock content %}
  </div>

image.png

image.png

image.png


42. Refactor View to add Email Field


>>Return to Menu

users > forms:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth. forms import UserCreationForm

class UserRegisterForm(UserCreationForm) :
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

image.png

users > views:

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('home')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {
            'form': form,
            'page': 'register',
        })

image.png

image.png

image.png

image.png


43. Install Crispy Forms to Style Template


>>Return to Menu

pip install django-crispy-forms

image.png


44. Register Crispy Forms in Project settings


>>Return to Menu

'crispy_forms',

image.png

CRISPY_TEMPLATE_PACK = 'bootstrap4'

image.png


45. Load Crispy Forms in Register page


>>Return to Menu

{% load crispy_forms_tags %}
{{ form | crispy}}

image.png

image.png


USERS APP - Login and Logout


46. Setup Project URL for Users URLs


>>Return to Menu

blog_project > urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
    path('user/', include('users.urls'))
]

image.png


47. Setup Login and Logout URLs with Class-based Views


>>Return to Menu

users > urls.py:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
]

image.png


48. Create Login page in Templates


>>Return to Menu

users > templates > users > login.html:

{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Login</legend>
                {{ form | crispy}}
            </fieldset> 
            <div class="form-group">
                <button class="btn btn-success" type="submit">Log In</button>
            </div>   
        </form>  
        <div class="border-top pt-3">
            <small class="text-muted">
                Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
            </small>
        </div>  
    </div>    
{% endblock content %}

image.png


49. Set Login redirect URL in Settings


>>Return to Menu

LOGIN_REDIRECT_URL = 'home'

image.png

image.png

image.png


50. Refactor Register View to Redirect to Login Page


>>Return to Menu

messages.success(request, 'You Account has been created! You can now Login.')
return redirect('login')

users > views.py:

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, 'You Account has been created! You can now Login.')
            return redirect('login')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {
            'form': form,
            'page': 'register',
        })

image.png

image.png

image.png


51. Create Logout Template


>>Return to Menu

users > templates > users > logout.html:

{% extends 'blog/base.html' %}
{% block content %}
    <div class="content-section">
        <h2>You have been logged out.</h2>
        <hr>
        <div class="border-top pt-3">
            <small class="text-muted">
                <a href="{% url 'login' %}" type="button" class="btn btn-danger">Login In Again</a>
            </small>
        </div>  
    </div>    
{% endblock content %}

image.png


52. Refactor base.html menu to show Logout option


>>Return to Menu

               <ul class="navbar-nav d-flex">
                    {% if user.is_authenticated %}
                        <li class="nav-item">
                        <a class="nav-link" href="{% url 'logout' %}">Logout</a>
                        </li>
                    {% else %}
                        <li class="nav-item">
                        <a class="nav-link {% if page == 'register' %}active{% endif %}" aria-current="registration" href="{% url 'register' %}">Register</a>
                        </li>
                        <li class="nav-item">
                        <a class="nav-link" href="{% url 'login' %}">Login</a>
                        </li>
                    {% endif %}    
                </ul>

image.png

image.png


53. Create View for Profile page


>>Return to Menu

users > views.py:

def profile(request):
    return render(request, 'users/profile.html', {})

image.png


54. Create HTML Template for Profile page


>>Return to Menu

users > templates > users > profile.html:

{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <h1>{{user.username}}</h1>   
{% endblock content %}

image.png


55. Create URL route for profile page


>>Return to Menu

users > urls.py:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('profile/', views.profile, name='profile'),
]

image.png


56. Set Profile menu in base.html


>>Return to Menu

blog > templates > blog > base.html:

              <ul class="navbar-nav d-flex">
                    {% if user.is_authenticated %}
                        <li class="nav-item">    
                            <a class="nav-link" href="{% url 'profile' %}">Profile</a>
                        </li>
                        <li class="nav-item">    
                            <a class="nav-link" href="{% url 'logout' %}">Logout</a>
                        </li>
                    {% else %}
                        <li class="nav-item">
                        <a class="nav-link {% if page == 'register' %}active{% endif %}" aria-current="registration" href="{% url 'register' %}">Register</a>
                        </li>
                        <li class="nav-item">
                        <a class="nav-link" href="{% url 'login' %}">Login</a>
                        </li>
                    {% endif %}    
                </ul>

image.png

image.png

image.png


57. Force User to be logged in before Access


>>Return to Menu

from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
    return render(request, 'users/profile.html', {})

users > views.py:

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, 'You Account has been created! You can now Login.')
            return redirect('login')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {
            'form': form,
            'page': 'register',
        })

@login_required
def profile(request):
    return render(request, 'users/profile.html', {})

image.png

blog_project > settings.py:

LOGIN_URL = 'login'

image.png

image.png


58. Create Profile Model


>>Return to Menu

users > models.py:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def _str__(self):
        return f'{self.user.username} Profile'

image.png


59. Install Pillow for Profile model Migration


>>Return to Menu

pip install Pillow

image.png


60. Run Profile model Migration


>>Return to Menu

python manage.py makemigrations

image.png

python manage.py migrate

image.png


POLLS APP


0-1. Using PULL_REQUEST_TEMPLATE.md


>>Return to Menu



# Description

- brief summary

# Details

- change 1
- change 2
- change 3

# General Notes

- any additional information or context

# Checklist

- [ ] New Changes to code
- [ ] Refactored Previous code
- [ ] Tests completed
- [ ] Documentation

# References

[Example](www.google.com)


0-2. Using GitHub Actions


>>Return to Menu






name: GitHub Actions
on: [push]
jobs:
  GitHub-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event."
      - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!"
      - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
      - name: Check out repository code
        uses: actions/checkout@v2
      - run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner."
      - run: echo "🖥️ The workflow is now ready to test your code on the runner."
      - name: List files in the repository
        run: |
          ls ${{ github.workspace }}
      - run: echo "🍏 This job's status is ${{ job.status }}."


0-3. Creating App project


>>Return to Menu

$ django-admin startproject mysite

image.png

Files are:

  • outer mysite/ : The outer mysite/ root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
  • manage.py: A command-line utility that lets you interact with this Django project in various ways.
  • inner mysite/ : The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).
  • mysite/init.py: An empty file that tells Python that this directory should be considered a Python package.
  • mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
  • mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
  • mysite/asgi.py: An entry-point for ASGI-compatible web servers to serve your project.
  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.


0-4. Starting Development Server


>>Return to Menu

$ python manage.py runserver

$ python manage.py runserver 8080
$ python manage.py runserver 0:8080
$ python manage.py runserver 0.0.0.0:8080
$ python manage.py runserver 192.168.0.2:8080

image.png image.png


0-5. Creating the Polls app


>>Return to Menu

$ python manage.py startapp polls

image.png


0-6. Write your first view


>>Return to Menu

from django.shortcuts import render
from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

image.png


0-7. Map your view to App URL


>>Return to Menu
To call the view, we need to map it to a URL, and for this we need a URLconf. To create a URLconf in the polls directory, create a file called urls.py.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

image.png


0-8. Include App URL in Base (Project) URL List


>>Return to Menu
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.

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

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

image.png

image.png

image.png


0-9. Deploying Migrations (set default db)


>>Return to Menu

$ python manage.py migrate

image.png

image.png

image.png

image.png


0-10. Creating models


>>Return to Menu

polls/models.py:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

image.png

IMPORTANT CODE


1-1. Basics


>>Return to Menu

#1.INSTALL VENV
$ python3 -m venv venv
$ source venv/bin/activate
(venv) $
#2.CREATE REQUIREMENTS
$ pip freeze > requirements.txt
$ cat requirements.txt
numpy==1.9.2
requests==2.7.0
#3.INSTALL DJANGO
$ python -m pip install Django
$ django-admin
#4.VIEW DJANGO VERSION
$ python -m django --version
#5.CREATE DJANGO PROJECT
$ django-admin startproject monthly_challenges
$ django-admin startproject mypage
~/desktop/server/django django-admin startproject mypage
#6.CREATE PROJECT APPS
$ python manage.py startapp challenges
#7.RUN LOCAL SERVER
$ python manage.py runserver
>>>>>
Django version 3.1.5, using settings 'mypage.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
class Room(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    pub_date = models.DateTimeField('date published')
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    thumb = models.ImageField(default='default.png', blank=True)
    ROOM_CATEGORIES = (
        ('YAC', 'AC'),
        ('NAC', 'NON-AC'),
        ('DEL', 'DELUXE'),
        ('KIN', 'KING'),
        ('QUE', 'QUEEN'),
    )
    category = models.CharField(max_length=3, choices=ROOM_CATEGORIES)

    place = models.OneToOneField(
        Place,
        on_delete=models.CASCADE,
        primary_key=True,
    )
User.objects.all()
User.objects.first()
User.objects.filter(username=‘Alex’)
User.objects.filter(username=‘Alex’).first()
user = User.objects.filter(username=‘Alex’).first()
user = User.objects.get(id=1)
user.id
user.pk
user.post_set.all()
user.post_set.create(title="", content="")
from blog.models import Post
from django.contrib.auth.models import User
AUTH_USER_MODEL = 'hotel.user'
{% if user.is_authenticated %}{% endif %}
// capture requirements to install
pip freeze > requirements.txt

// install requirements from requirements.txt
pip install -r requirements.txt

// or
$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt
pip freeze or pip list

$ python manage.py makemigrations

$ python manage.py migrate

$ python manage.py sqlmigrate weblog 0001

$ python manage.py shell

$ pip install django django-shortcuts
#python decouple module

#Create Migrations
$python manage.py migrate 

#Create SuperUser
$python manage.py createsuperuser
Username: 
Email address:
Password:
from django.shortcuts import render
from hotel.models import User, Receptionist, Room, RoomStatus, RoomType, Booking, Payment, PaymentType, Reservation

def check_availability(room, start_time, end_time):
    check = []
    booking_list = Reservation.objects.filter(room_id=room)
    for booking in booking_list:
        if booking.start_time > end_time or booking.end_time < start_time:
            check.append(True)
        else:
            check.append(False)
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    username = models.CharField(max_length=64, unique=True)
    email = models.EmailField(max_length=64, unique=True)
    phone_number = models.CharField(max_length=64, unique=True)
    password = models.CharField(max_length=64)
    otp_code = models.CharField(max_length=64, default=None, unique=True, null=True)
    email_verified = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_superadmin = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, null=True)

    def __str__(self):
        return f'User: {self.username.title()}'
AUTH_USER_MODEL = 'hotel.user'
INSTALLED_APPS = [
    'hotel.apps.HotelConfig',
    'aa.apps.AaConfig',
    'booking.apps.BookingConfig',
    'payment.apps.PaymentConfig',
    'logs.apps.LogsConfig',
]


1-2. List View


>>Return to Menu

hotel > views.py:

from django.shortcuts import render
from django.views.generic import ListView
from .models import User, Receptionist, Room, RoomStatus, RoomType, Booking, Payment, PaymentType, Reservation


class RoomList(ListView):
    model = Room       

class BookingList(ListView):
    model = Booking

image.png

hotel > urls.py:

from django.urls import include, path
from . import views


urlpatterns = [
    path('', views.homepage, name='homepage'),
    path('rooms/', views.RoomList.as_view(), name='room_lists'),
    path('bookings/', views.BookingList.as_view(), name='booking_lists'),
]

hotel > templates > hotel > room_list.html:

{% extends "hotel/base_dashboard.html" %}
{% load static %}

{% block heading %}
    <h1>Room List</h1>
{% endblock heading %}

{% block main %}
    {% for room in room_list %}
        <h2>Room: {{room.room_no | title}}</h2>
    {% endfor %}
{% endblock main %}

image.png

image.png


1-3. DateField Widget


>>Return to Menu

DateField, TimeField and DateTimeField:

 from django import forms

class DateInput(forms.DateInput):
    input_type = 'date'

class TimeInput(forms.TimeInput):
    input_type = 'time'

class DateTimeInput(forms.DateTimeInput):
    input_type = 'datetime-local'


class MyForm(forms.Form):
    my_field = forms.DateTimeField(widget=DateTimeInput)
OR
class MyForm(forms.Form):
    class Meta:
        widgets = {'my_field ' : DateTimeInput()}

DateTimeField:

from django import forms

class BookingForm(forms.Form):
    widget = forms.DateTimeInput(attrs={
            'class': 'form-control',
            'type': 'datetime-local',
            'style': 'max-width: 300px',
        })

    ROOM_TYPES = (
        ('SINGLE', 'SINGLE'),
        ('DOUBLE', 'DOUBLE'),
        ('KING', 'KING'),
        ('VIP', 'VIP'),
        ('PRESIDENTIAL', 'PRESIDENTIAL'),
    )
    room_type = forms.ChoiceField(choices=ROOM_TYPES, required=True)
    customer_id = forms.IntegerField(required=True)
    payment_id = forms.IntegerField(required=True)
    start_date = forms.DateTimeField(widget=widget, required=True)
    end_date = forms.DateTimeField(widget=widget, required=True)

image.png

image.png

[
    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
    '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
    '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
    '%m/%d/%y %H:%M',        # '10/25/06 14:30'
]


DJANGO REST FRAMEWORK (DRF)


2-1. PIPENV


>>Return to Menu

Install PIPENV:

pip install pipenv

Create the virtualenv:

pipenv --python 3.10.3

image.png

Activate the virtual env:

pipenv shell

source $(pipenv --venv)/bin/activate

image.png

Deactivate the virtual env:

exit

image.png

View location of the virtualenv:

pipenv --venv

Delete the virtualenv:

pipenv --rm

rm -rf /Users/ifeanyiomeata/.local/share/virtualenvs/docker_drf-yNZHhWWe

image.png


2-2. Create Django Project


>>Return to Menu

django-admin startproject drf_project

pipenv install django django-shortcuts


2-3. Create Django app


>>Return to Menu

python manage.py startapp drf


2-4. Run Migrations


>>Return to Menu

python manage.py makemigrations
python manage.py sqlmigrate
python manage.py migrate

django mm
django m

image.png


2-5. Create Superuser


>>Return to Menu

python manage.py createsuperuser

image.png


2-6. Install Django Rest Framework


>>Return to Menu

pipenv install djangorestframework

image.png


2-7. Add Rest_framework and apps to settings.py


>>Return to Menu

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'drf.apps.DrfConfig',
]

image.png


2-8. Set Project URLs


>>Return to Menu

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

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

image.png


2-9. Create Model


>>Return to Menu

from django.db import models


class User(models.Model):
    username = models.CharField(max_length=200, unique=True)
    firstname = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    gender = models.CharField(max_length=10)
    age = models.IntegerField()
    password = models.CharField(max_length=200)
    otp_code = models.CharField(max_length=6)

    def __str__(self):
        return self.username

image.png


2-10. Register Model in Admin


>>Return to Menu

from django.contrib import admin
from .models import User


admin.site.register(User)

image.png


2-11. Run server


>>Return to Menu

python manage.py runserver

django r

image.png

image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022