Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

Django IntroductionChapter 4. Create CRUD Web Application

Generic View Basic Attributes

Generic View Basic Attributes

Attributes of Django Generic Views

Attributes in generic views are key design elements when you create a new view using generic views. For example, you can define which template file will be used for the view or which model will be used for the view. Required or optional attributes are different in each generic view.

Generic View Basic Attributes

There are many attributes you can use when creating new views with generic views. The following are basic frequently used attributes:

model

The model attributes define the model for which the view will display data. The model attribute can be replaced by the queryset attribute. The model attribute is defined in SingleObjectMixin and MultipleObjectMixin.

queryset

The queryset attribute is also used to define the model used for the view; however, queryset gives you more functionalities using several methods.

  • all(): retrieves all objects. 'queryset = ModelName.objects.all()' give the same result as 'model = ModelName'
  • filter(): returns objects that match the given lookup parameters
  • order_by(): returns objects in order. To reverse the order, you can use "-". For example, if you want to order based on the name field, use order_by('name'). If you want to reverse the order, you can use order_by('-name').

The queryset attribute is defined in SingleObjectMixin and MultipleObjectMixin.

template_name

The template_name attribute is used to define the path of an HTML template for the view. The path should be described as a relative path from the template directory set in the settings.py file.

For example, when you set the 'templates' directory in settings.py as the main directory for the templates and directly place the template file named template.html in the 'templates' directory, you can just set it like 'template_name = template.html'.

When you want to use a subdirectory, use the subdirectory name before the template file name, like 'template_name = subdir/template.html'.

If you don't specify this attribute, Django uses a predefined path for the template.
For example, if an app name is employee_learning, a model name is LearningCourse, and a generic view is ListView, the inferred HTML template will be employee_learning/learningcourse_list.html.

To organize template files better, specifying template_name is recommended.

The template_name attribute is defined in TemplateResponseMixin.

context_object_name

The context_object_name attribute is used to add a name to the object passed to template files.

For example, the default object name is object in DetailView. In DetailView, object_list contains the list of objects. You can call objects defined in related views using 'object' or 'object_list' in Django templates.

When you specify context_object_name in your view, you can call the objects using the name you defined.

Even after specifying context_object_name, you can still call the objects using 'object' or 'object_list'. The context_object_name attribute gives you an additional name that can be used in your template files.

The context_object_name attribute is defined in SingleObjectMixin and MultipleObjectMixin.

We'll explain about context_object_name in detail later in this chapter.

fields

The fields attribute is used to define model fields shown in the input form pages (create page and update page). This attribute is required if you are generating the form class automatically.

The fields attribute is defined in ModelFormMixin.

success_url

The success_url is used to define the URL to redirect to when the form is successfully processed. This attribute is usually required for generic editing views.

reverse_lazy() is often used for this argument to resolve Django URL names into URL paths. Django URL names are defined in urls.py, which will be explained later.

The fields attribute is defined in FormMixin.

IdeaNote : Generic Views Inheritance

Each generic view has attributes and methods that are inherited from their ancestor views or mixins (a set of methods or attributes that can be "mixed in" to a class).

Generic Views Inheritance

In the Django documentation, you may not be able to find attribute information under each generic view section.

Attribute or method information is written in the ancestor classes (views or mixins) in the Django documentation.

Django documentation reference: ListView

Django documentation reference: MultipleObjectMixin

Django documentation reference: TemplateResponseMixin

Practice

In this practice, we'll create views using Django generic views. We also use the LearningCourse model we designed in the previous chapter.

1. Import generic views and models used in this view

All generic views are stored in django.view.generic. Import five generic views

  • ListView
  • DetailView
  • CreateView
  • UpdateView
  • DeleteView

Also, import the LearningCourse model.

The yellow lines below are the new code.

employee_learning/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import LearningCourse

2. Create the CourseList and CourseDetail views

As a simple implementation, you set the following three attributes for both views.

  • model: You can also use queryset instead of model.
  • template_name: We haven't created HTML templates, but let's assume we'll create the employee_learning directory to store HTML templates.
  • context_object_name: 'course_object_list' and 'course_object' will be used later in the template section of this chapter.

employee_learning/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import LearningCourse

class CourseList(ListView):
    model = LearningCourse
    template_name = 'employee_learning/course_list.html'
    context_object_name = 'course_object_list'

class CourseDetail(DetailView):
    model=LearningCourse
    template_name = 'employee_learning/course_detail.html'
    context_object_name = 'course_object'

3. Create the CourseCreate, CourseUpdate and CourseDelete views

As CreateView, UpdateView, and DeleteView are generic editing views, the required attributes differ from those for ListView and DetailView. You don't need context_object_name, but you need to add success_url to define the URL to redirect when the data submission action is successful. For CreateView and UpdateView, you also need to add the fields attribute to specify which field should be shown in the input form.

As we use reverse_lazy for success_url, we need to import it first.

employee_learning/views.py
  :
from .models import LearningCourse
from django.urls import reverse_lazy
  :
class CourseDetail(DetailView):
    model=LearningCourse
    template_name = 'employee_learning/course_detail.html'
    context_object_name = 'course_object'

class CourseCreate(CreateView):
    model=LearningCourse
    template_name = 'employee_learning/course_create.html'
    fields=('title', 'level', 'employee')
    success_url=reverse_lazy ('course_list')

class CourseUpdate(UpdateView):
    model=LearningCourse
    template_name = 'employee_learning/course_update.html'
    fields=('title', 'level','employee')
    success_url=reverse_lazy ('course_list')

class CourseDelete(DeleteView):
    model=LearningCourse
    template_name = 'employee_learning/course_delete.html'
    success_url=reverse_lazy ('course_list')

To see the output of these views, you need to create urls.py and Django templates, which will be explained in the following sections.


You can also learn this topic offline. Click AmazonKindle.

Tags:

views.py

Django Generic Views

Attributes

Django Introduction
Course Content

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment