0% found this document useful (0 votes)
24 views

Full Stack Development-Module 2

MODELS AND ADMIN INTERFACES

Uploaded by

sunil.ise
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Full Stack Development-Module 2

MODELS AND ADMIN INTERFACES

Uploaded by

sunil.ise
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Template Definition

In Django, templates are text files containing a mix of static HTML markup and
dynamic content generated using Django's template language. They serve as the
presentation layer of web applications, allowing developers to create dynamic web
pages by inserting data from the server side into predefined placeholders within
the HTML structure. Templates facilitate the separation of concerns between the
presentation layer and the business logic, promoting a clean and maintainable
codebase. Django's template system includes features like template tags, template
variables, template inheritance, and filters, providing developers with the tools
needed to create dynamic and interactive web applications efficiently.
Django Template System
The Django template system is a powerful tool for generating dynamic HTML content
in web applications. Here's an overview:

Purpose: The template system allows developers to separate the presentation layer
from the business logic in Django web applications. It facilitates the creation of
HTML pages with dynamic content by combining static HTML markup with template
tags, variables, filters, and control structures.

Syntax: Django templates use a syntax similar to Python, but with special constructs
for embedding dynamic content. Template variables are enclosed in double curly
braces ({{ }}), while template tags are enclosed in curly braces with percent signs
({% %}). Template tags control the logic and flow of the template, allowing for loops,
conditionals, includes, and more.

Context: When rendering a template, Django expects a context, which is a dictionary


containing data to be displayed in the template. Views in Django pass data to
templates by creating a context dictionary and rendering the template with that
context. Template variables within the template file access data from this context.
Django Template System

Template Inheritance: Django supports template inheritance, allowing developers to


create a base template with common elements like headers, footers, and navigation
bars. Child templates can then extend the base template and override specific blocks
to customize their content while maintaining consistency across the site.

Filters: Filters modify the output of template variables or template tags. They allow
for formatting, manipulation, and customization of data displayed in the template.
Django provides a range of built-in filters for common tasks like date formatting,
string manipulation, and more. Custom filters can also be defined to suit specific
application requirements.

Overall, the Django template system provides a flexible and efficient way to create
dynamic HTML content in web applications, promoting code reuse, maintainability,
and separation of concerns.
Template Basics
Template Variables:
Definition: Template variables are placeholders within Django templates that
represent dynamic data to be rendered.
Example: Suppose you have a context dictionary in your view containing the following
data:

Python :
context = { 'name': 'John',
'age': 30,
'city': 'New York' }

Html:
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<p>City: {{ city }}</p>
Template Basics
Template Tags:
Definition: Template tags are constructs within Django templates that control the
logic and flow of the template.

Example: Using a loop to iterate over a list in the template:

<ul> {% for item in items %}


<li>{{ item }}</li>
{% endfor %}

Filters:
Definition: Filters modify the output of template variables or template tags.
Example: Using the date filter to format a date

<p>{{ birthday|date:"F j, Y" }}</p>

Here, birthday is a variable containing a date, and date:"F j, Y" formats it as "Month
Day, Year" (e.g., "January 1, 2023").
Template Basics
Blocks:
Definition: Blocks allow templates to be extended and overridden in a hierarchical
manner using template inheritance.

Example: Define a base template (base.html) with a block:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}
<p>This is the base content.</p>
{% endblock %}
</body>
</html>
Template Basics
Then, extend the base template in another template (child.html) and override the
blocks:

{% extends "base.html" %}

{% block title %}Child Page{% endblock %}

{% block content %}
<p>This is the content of the child page.</p>
{% endblock %}
Template Basics
Template Language: Django comes with its own template language that allows developers to
dynamically generate HTML pages. This language includes template tags, template
variables, filters, and control structures like loops and conditionals.

Template Files: In Django, templates are typically stored in the templates directory within each
Django app. These template files have a .html extension and contain a mix of HTML code
and Django template language syntax.

Rendering: Django uses a template engine to render templates and generate HTML
dynamically. The most commonly used template engine in Django is the Django Template
Language (DTL), but other engines like Jinja2 can also be integrated.

Context: Templates in Django are rendered with a context, which is a dictionary containing
data to be displayed in the template. Views in Django pass data to templates by creating a
context dictionary and rendering the template with that context.

Template Inheritance: Django supports template inheritance, allowing developers to create a


base template with common elements like headers, footers, and navigation bars. Child
templates can then extend the base template and override specific blocks to customize their
content while maintaining consistency across the site.
Template Loading
1.Configure Template Directory: Define template locations in
settings.py using TEMPLATES setting. Each directory holds
multiple templates. (For Template Configuration code refer next slide)
2.Create HTML Templates: Design HTML templates within these
directories, using Django's templating language to embed Python
for dynamic content.
3.Render Templates in Views: Load templates in Python views,
pass data using a context dictionary, and return HTTP responses
with the rendered templates.

syntax: render(request, template.html , context) (or)

from django.template import loader


template=loader.get_template(template.html)
template.render(context, request)

Eg: display ordered and unordered list


Template Loading
Template Inheritance
Template inheritance in Django is a mechanism that allows you to

create a base template with common layout and structure, and then extend

or override specific sections of that template in child templates. This

approach promotes code reuse and maintainability by enabling you to

define a base design once and then customize it as needed for different

pages or components within your website or web application.


Template Inheritance
1.Create Base Template: Design a base template with shared elements like header
and footer.

2.Identify Override Blocks: Mark sections for customization using {% block %}


tags.

3.Extend Base Template: Use {% extends %} to inherit the base template in child
templates.

4.Override Blocks: Customize specific sections in child templates using {% block


%} tags.

5.Optional Default Content: Include default content in blocks for flexibility.

6.Render Child Template: Specify the child template in views, and Django will
combine it with the base template.

Eg: application of layout,home,about,contact html pages


TheMVT Development Pattern
MVT (Model-View-Template) is a design pattern used by Django, a
popular Python web framework. Here are the steps involved in
developing with the MVT pattern:

Model:

 Define your data structure by creating Django models. Models


represent the structure and behavior of your application's data.
Each model typically corresponds to a database table, and it
includes fields representing the attributes of the data.
 Create classes that inherit from Django's models.Model class.
 Define fields in these classes using Django's built-in field types
like CharField, IntegerField, ForeignKey, etc.
 Optionally, define methods on models to encapsulate business
logic related to the data.
MVT Development Pattern
View:
• Create views to handle user requests and generate responses.
Views are Python functions or classes that receive HTTP requests
and return HTTP responses.

• Write view functions or methods that handle specific URLs or


routes in your application.

• Retrieve data from the database using Django's ORM (Object-


Relational Mapping) system.

• Perform any necessary data processing or manipulation.

• Render templates to generate HTML responses, or return


JSON/XML responses for APIs.
MVT Development Pattern
Template:

• Design HTML templates to define the presentation layer of your


application.
• Use Django's template language to embed dynamic content and logic
within HTML.
• Extend base templates to create a consistent layout across multiple
pages.
• Include template tags and filters to perform operations like looping over
data, conditional rendering, etc.
• Pass data from views to templates using context variables.
• Render templates with data to generate the final HTML sent to the client.

In summary, the MVT pattern in Django divides the development process


into three main components: Models for data handling, Views for request
handling and business logic, and Templates for presentation and user
interface design. This separation of concerns helps to maintain a clean and
MVT Development Pattern
Template:

• Design HTML templates to define the presentation layer of your


application.
• Use Django's template language to embed dynamic content and logic
within HTML.
• Extend base templates to create a consistent layout across multiple
pages.
• Include template tags and filters to perform operations like looping over
data, conditional rendering, etc.
• Pass data from views to templates using context variables.
• Render templates with data to generate the final HTML sent to the client.

In summary, the MVT pattern in Django divides the development process


into three main components: Models for data handling, Views for request
handling and business logic, and Templates for presentation and user
interface design. This separation of concerns helps to maintain a clean and
Models
1. Definition and Representation:
1. Models in Django are Python classes representing the
structure of application data.
2. Each model class typically corresponds to a database table,
with class attributes defining fields in that table.

2. Data Management and Relationships:


1. Models enable CRUD operations (Create, Read, Update,
Delete) for interacting with the database.
2. Relationships between data entities can be defined within
models, allowing for complex data structures and
associations.
Configuring databases

Configuration in settings.py: Define database settings like


engine and connection details.

Model Definitions: Use Python classes to define database tables


and fields.

Migration Management: Create and apply migrations to sync


database schema with model changes.

Multiple Database Support: Configure and utilize multiple


databases for different needs.

Performance Optimization: Utilize Django's tools for database


performance enhancement, including indexing and query
optimization.
Defining and Implementing Models
Define Models:
Create Python classes in your Django app's models.py file.
Each class represents a database table.
Define class attributes as fields, specifying field types (e.g.,
CharField, IntegerField).

Add Field Attributes:


Specify additional field attributes like max_length, default values,
or nullability.
Use Django's built-in field types or custom ones if needed.

Define Relationships:
Establish relationships between models using ForeignKey,
OneToOneField, or ManyToManyField.
ForeignKey establishes a many-to-one relationship, OneToOneField
creates a one-to-one relationship, and ManyToManyField defines a
many-to-many relationship.
Defining and Implementing Models
4. Run Migrations:

 Generate migration files using python manage.py


makemigrations.
 Apply migrations to create or modify database tables using
python manage.py migrate.

5. Interact with Models:

 Use Django's ORM (Object-Relational Mapping) to interact


with models.
 Create, retrieve, update, or delete objects using model
methods or queryset API.
 Incorporate models into views, forms, or other parts of your
Django application for data management.
Basic Data Access
Creating Objects:

• To create an object in Django, import the appropriate model class and instantiate
it by passing values for each field.

class Publisher(models.Model):
name = models.CharField(maxlength=30)
address = models.CharField(maxlength=50)
city = models.CharField(maxlength=60)
state_province = models.CharField(maxlength=30)
country = models.CharField(maxlength=50)
website = models.URLField()
from books.models import Publisher

p1 = Publisher(name='Addison', address='75 Arlington St.',


city='Boston', state_province='MA', country='U.S.A.',
website='http://www.Addison.com/')
Basic Data Access
Saving Objects:

To save an object to the database, call the save() method on the


model instance. This action executes an SQL INSERT statement to
store the data in the database.
Eg:
p1.save()

Retrieving Objects:

Use the Publisher.objects attribute to access the database and


retrieve objects. To fetch all records from a model, use the all()
method, which executes an SQL SELECT statement.
Eg:
publisher_list = Publisher.objects.all()
Basic Data Access
Viewing Retrieved Objects:

The retrieved objects can be viewed as a list of model instances. By default, the
output shows a list of model objects.

print(publisher_list)
# Output: [<Publisher: Publisher object>, <Publisher: Publisher object>]

Executing SQL Behind the Scenes:

Django's ORM abstracts the SQL commands, automatically generating the


appropriate SQL statements (such as INSERT for saving objects and SELECT for
retrieving objects) to interact with the database.

# Saving the object


p1.save() # Executes: INSERT INTO publisher ...

# Retrieving objects
publisher_list = Publisher.objects.all() # Executes: SELECT * FROM publisher
Adding Model String Representations
Purpose and Functionality:

The __str__() method in Django models provides a


human-readable string representation for instances,
enhancing their clarity and usability across the Django
application.

Implementation and Importance:

Adding a __str__() method to a model ensures effective


representation of instances, improving developer
experience, debugging, logging, and identification in
various Django interfaces.
Adding Model String Representations
The __str__() method in Django models is used to define a human-
readable string representation of the model instance. This method is
particularly useful when you print the model instance or when it is
displayed in the Django admin interface.

Example: Defining a __str__() Method for a Book Model


Model Definition: Let's define a Book model with fields for title, author, &
publication_date.

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publication_date = models.DateField()

def __str__(self):
return self.title
Adding Model String Representations
Creating Instances:

Create instances of the Book model and save them to the database

# Creating book instances

book1 = Book(title='The Great Gatsby', author='F. Scott Fitzgerald',


publication_date='1925-04-10')
book1.save()

book2 = Book(title=‘The Django', author='George Orwell',


publication_date='1949-06-08')
book2.save()
Adding Model String Representations
Using the __str__() Method:

When you print a Book instance or view it in a list, Django uses the
__str__() method to display the title.

>>> from books.models import Book


>>> book1 = Book.objects.get(title='The Great Gatsby')
>>> print(book1)
The Great Gatsby

>>> books = Book.objects.all()


>>> for book in books:
... print(book)
...
The Great Gatsby
The Django
Inserting/Updating Data
1. Creating an Instance:

To insert a row into the database, instantiate your model class with the
necessary attributes using keyword arguments. This action does not
interact with the database.

p = Publisher(name='Apress', address='2855 Telegraph Ave.',


city='Berkeley', state_province='CA', country='U.S.A.',
website='http://www.apress.com/')

2. Saving to the Database:

To save the instance to the database and perform an SQL INSERT


statement, call the instance's save() method.

p.save()
Inserting/Updating Data
3. SQL Translation:
The save() method translates to an SQL INSERT statement, adding the
record to the database with an autogenerated primary key.

INSERT INTO book_publisher (name, address, city, state_province,


country, website) VALUES ('Apress', '2855 Telegraph Ave.', 'Berkeley',
'CA', 'U.S.A.', 'http://www.apress.com/');

4. Primary Key Assignment:


After the initial save, Django assigns the autogenerated primary key
value to the instance’s id attribute.

p.id # e.g., 52
Inserting/Updating Data
5. Updating an Instance:
To update an existing record, modify the instance attributes and call the
save() method again, which performs an SQL UPDATE statement instead
of an INSERT.

p.name = 'Apress Publishing'


p.save()

UPDATE book_publisher SET name = 'Apress Publishing', address = '2855


Telegraph Ave.', city = 'Berkeley', state_province = 'CA', country =
'U.S.A.', website = 'http://www.apress.com' WHERE id = 52;
Selecting and Deleting Objects
1. Data Retrieval Importance: Accessing and analyzing data is crucial for its
usefulness beyond creation and updating.

2. Django's Simple Retrieval: Use all() method through the model's manager
(e.g., Publisher.objects.all()) to easily retrieve all data for a specific model.

3. SQL Translation and Field Selection: Publisher.objects.all() in Django


translates into SQL, explicitly selecting fields for improved performance.

4. Explicit Field Listing: Django prefers explicit field listing over implicit
retrieval, aligning with Pythonic principles and enhancing performance.

5. Component Understanding and QuerySet Concept: Deconstructing


Publisher.objects.all() reveals Django's querying framework, where the result,
though resembling a list, is actually a QuerySet, essential for understanding
querying behavior.
Filtering Data
Introduction to Filtering Data: While retrieving all objects has its
utility, often we need to work with a subset of data. This is achieved
using the filter() method in Django.

Basic Filtering with Single Argument: The filter() method accepts


keyword arguments, which are translated into SQL WHERE
clauses. For example, Publisher.objects.filter(name="Apress
Publishing") retrieves the publisher with the specified name.

# Retrieve the publisher with the name "Apress Publishing"

Publisher.objects.filter(name="Apress Publishing")
Filtering Data
Multiple Argument Filtering: You can pass multiple arguments into filter() to
further narrow down the data. These arguments are translated into SQL AND
clauses, allowing for more specific filtering.

# Retrieve publishers located in the U.S.A. and in the state of California

Publisher.objects.filter(country="U.S.A.", state_province="CA")

Different Lookup Types: By default, Django uses the SQL = operator for exact match
lookups. However, other lookup types are available, such as __contains, which
translates to an SQL LIKE statement for partial string matches.

# Retrieve publishers with names containing the substring "press"

Publisher.objects.filter(name__contains="press")
Filtering Data
Special Lookup Types: Django supports various lookup types, including case-
insensitive matching (icontains), string prefix matching (startswith), string suffix
matching (endswith), and range queries (range). These provide versatile options
for filtering data based on specific criteria.

# Retrieve publishers with names containing the substring "press" in a


case-insensitive manner
Publisher.objects.filter(name__icontains="press")

# Retrieve publishers with names starting with "Addison"


Publisher.objects.filter(name__startswith="Addison")

# Retrieve publishers with names ending with "Publishing"


Publisher.objects.filter(name__endswith="Publishing")

# Retrieve publishers with IDs ranging from 1 to 100


Publisher.objects.filter(id__range=(1, 100))
Retrieving Single Object
Introduction to Retrieving Single Objects: In certain scenarios, fetching only one
object is necessary. Django provides the get() method for this purpose.

Usage of the get() Method: Utilize the get() method to retrieve a single object based
on specified criteria. For instance,
Publisher.objects.get(name="Apress Publishing")
fetches the publisher with the name "Apress Publishing".

Exception Handling for Multiple Objects: If the query results in multiple objects,
invoking get() will raise an exception.
For example,
Publisher.objects.get(country="U.S.A.")
will raise an AssertionError due to multiple matches.

Handling Non-existent Objects: Similarly, if the query returns no objects, a


DoesNotExist exception is raised. For instance,

Publisher.objects.get(name="Penguin")
will raise a DoesNotExist exception as there's no publisher with the name "Penguin".
Ordering Data

Introduction to Ordering Data: Django's order_by() method allows for


arranging retrieved objects in a specified order, enhancing the presentation of
data.

Usage of order_by(): Utilize order_by() to sort data based on specific fields,


such as Publisher.objects.order_by("name"), which orders publishers
alphabetically by name.

Multiple Field Ordering: Data can be ordered by multiple fields for more
nuanced sorting, as shown by Publisher.objects.order_by("country",
"address"), which orders publishers first by country and then by address.
Reverse Ordering: Reverse ordering is achievable by prefixing the field
name with a minus sign, as demonstrated by
Publisher.objects.order_by("-name"), sorting in reverse alphabetical order
by name.
Ordering Data

Default Ordering: Django allows for setting a default ordering for a


model using the Meta class, reducing the need for repetitive
ordering specification. For example, class Meta: ordering =
["name"] sets the default ordering for the Publisher model by
name.
class MyModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

class Meta:
ordering = ["name"]
Ordering Data

Default Ordering: Django allows for setting a default ordering for a


model using the Meta class, reducing the need for repetitive
ordering specification. For example, class Meta: ordering =
["name"] sets the default ordering for the Publisher model by
name.
class MyModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

class Meta:
ordering = ["name"]
Chaining Lookups

Chaining Lookups:
Chaining allows combining multiple QuerySet methods to refine
data retrieval.

This means you can filter the data first and then order the filtered
results, or vice versa.

Chained queries are executed in the sequence they are chained.

Example:
Publisher.objects.filter(country="U.S.A.").order_by("-name")

filters publishers from the U.S.A. and then orders them by name in
descending order.
Slicing Data

List Slicing Syntax:

Python's list slicing syntax can be applied to Django


QuerySets to achieve this.

Syntax: QuerySet[start:end]
where start is the starting index and end is the ending index.

Example:
Publisher.objects.all()[0] retrieves the first publisher.
Deleting Objects
Deleting Single Objects:

To delete a single object, call the delete() method on the model


instance.

apress = Publisher.objects.get(name="Addison-Wesley")
apress.delete()

Bulk Deletion: To delete multiple objects, call delete() on a


QuerySet.

publishers = Publisher.objects.all()
publishers.delete()

Permanent Deletion: Deletions using delete() are permanent and


cannot be undone
Deleting Objects
Active Flags as an Alternative: Instead of deleting objects,
add an "active" flag to your model to indicate
active/inactive status.
class Publisher(models.Model):
name = models.CharField(max_length=100)
active = models.BooleanField(default=True)
To "delete" an object, set the active field to False.
apress = Publisher.objects.get(name="Addison-Wesley")
apress.active = False
apress.save()
Filter queries to retrieve only active objects.
active_publishers = Publisher.objects.filter(active=True)
Which of the following commands is used to install Django using pip?
a) pip install django
b) pip get django
c) pip setup django
d) pip configure django

Which command is used to create a new virtual environment in Python?


a) python -m venv myenv
b) python create venv myenv
c) python new venv myenv
d) python setup venv myenv

Which command is used to run a Django development server?


a) python manage.py runserver
b) django-admin runserver
c) python startserver
d) django runserver
In Django, where do you configure database settings?
a) settings.py
b) urls.py
c) models.py
d) views.py

Which of the following is not a valid template tag in Django?


a) {% if %}
b) {% for %}
c) {% while %}
d) {% block %}

In Django, what does 'loose coupling' refer to?


a) The independence of components such that changes in one part do not
requirechanges in another
b) Strong interdependencies between different components
c) Combining unrelated functions into a single module
d) Using multiple URL patterns for a single view
Which of the following is true about Django URL Confs?
a) They map URLs to Python functions
b) They map URLs to HTML templates
c) They map URLs to database models
d) They map URLs to CSS files

What is the primary design pattern followed by Django?


a) MVC
b) MVVM
c) MVT
d) MVP

Which of the following is a web framework for building web applications?


a) Flask
b) Django
c) Ruby on Rails
d) All of the above
Module 3 : Django Admin Interfaces and Model forms

Activating Admin Interfaces


Step 1: Add Admin Metadata to Your Models
Not all models are suitable or necessary to be editable via the admin interface.
Therefore, you need to mark those models that should have an admin interface
by adding an inner Admin class to the model. Here's how to do it:
*Define Your Model:
o Create or update your model by defining its fields. For example,
consider a Book model

class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True)
authors = models.ManyToManyField(Author)
*Add the Admin Class:
 Add an inner Admin class to the model. This class can be empty for now (using
pass), which indicates that the model should be included in the admin interface
with default options.
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True)
authors = models.ManyToManyField(Author)
class Admin:
pass
(or) Model Registration:
 You can register your models with the admin interface to make
them manageable via the admin site. This is done using the
admin.site.register() function. from django.contrib import admin
from .models import Book

admin.site.register(Book)
Step 2: Install the Admin Application
To use the admin interface, you need to add the admin application to
your project settings and sync the database:
*Modify INSTALLED_APPS:
o Open your settings.py file and add django.contrib.admin to the
INSTALLED_APPS list

INSTALLED_APPS = [
...
'django.contrib.admin',
...
]

*Run syncdb Command:


 Run the syncdb command to create the necessary database
tables for the admin interface.

python manage.py syncdb


*Run syncdb Command:
 Run the syncdb command to create the necessary database
tables for the admin interface.

python manage.py syncdb


(or)
*Create and Apply Migrations:
 Run the following commands to create migration files for your
models and apply them to the database.

python manage.py makemigrations


python manage.py migrate
* Create a Superuser: If you haven’t already created a superuser, you can do so
with:
python manage.py createsuperuser
Step 3: Add the URL Pattern to urls.py
The URL configuration remains similar, but here's a
slightly updated way to include the admin URLs:
Edit urls.py:
o Open your project's urls.py file and add the
following lines to include the admin URLs:
from django.contrib import admin
from django.urls import path

urlpatterns = [
...
path('admin/', admin.site.urls),
...
]
Step 4 : Running the Development Server
Start your development server:

python manage.py runserver

Using Admin Interfaces : Demonstrate with Eg


Managing Users, Groups, and Permissions
in the Admin Interface
 User Management: Through the admin interface,
you can add new users, edit existing users, and
assign them to groups.
 Group Management: You can create groups and
assign specific permissions to these groups.
 Permission Assignment: Permissions can be
assigned to users or groups through the admin
interface, giving you fine-grained control over
what each user can do.
Example Use Cases
1. Superuser:
o Capabilities: Can manage all aspects of the admin
interface without restrictions.
o Flags: is_active=True, is_staff=True, is_superuser=True.
2. Staff User:
o Capabilities: Can access the admin interface but only
has permissions granted explicitly.
o Flags: is_active=True, is_staff=True, is_superuser=False.
3. Regular User:
o Capabilities: Cannot access the
Customizing the Admin Interface for the Book Model in Django

 Create or update the admin.py file in your app directory. This file
is used to register your models with the admin site and customize
their display.
from django.contrib import admin
from .models import Book, Publisher, Author

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)

admin.site.register(Book, BookAdmin)
admin.site.register(Publisher)
admin.site.register(Author)
Explanation:
 Imports: Import the admin module and your models (Book,
Publisher, Author).
 BookAdmin Class:
o list_display = ('title', 'publisher', 'publication_date'): Specifies
the columns to display in the list view for the Book model.
o list_filter = ('publisher', 'publication_date'): Adds filters for
publisher and publication_date on the right side of the list
view.
o ordering = ('-publication_date',): Orders the books by
publication_date in descending order.
o search_fields = ('title',): Adds a search box to search by title.
 Registration: Register the Book model with the custom
BookAdmin class. Also, register the Publisher and Author models
with the admin site.
create a Django model for an employee and
customize it to include search functionality,
list display options, and add filters, you can
follow these steps:
# models.py
from django.db import models

class Employee(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
department = models.CharField(max_length=100)
job_title = models.CharField(max_length=100)
date_hired = models.DateField()
salary = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return f"{self.first_name} {self.last_name}
# admin.py
from django.contrib import admin
from .models import Employee

class EmployeeAdmin(admin.ModelAdmin):

search_fields = ['first_name', 'last_name', 'email', 'department',


'job_title']

list_display = ['first_name', 'last_name', 'email',


'department', 'job_title', 'date_hired', 'salary']

list_filter = ['department', 'job_title', 'date_hired']

admin.site.register(Employee, EmployeeAdmin)
Django Model Fields
Django Model Fields
Django Model Relationship Fields
Django Model Field Options
class Author(models.Model):
id = models.AutoField(primary_key=True) # primary_key example
name = models.CharField(max_length=100)
email = models.EmailField(unique=True, null=True, blank=True) # null and blank
example

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateField(null=True, blank=True) # null and blank example
price = models.FloatField(default=0.0) # default example
status = models.CharField(
max_length=1,
choices=[
('D', 'Draft'),
('P', 'Published'),
('W', 'Withdrawn')
],
default='D' # choices and default example
)
description = models.TextField(blank=True) # blank example
Customizing Admin Interfaces in Django
Search Fields:
o Enables searching through specified fields in the admin list
view.
o Enhances data retrieval efficiency.
List Display:
o Specifies which fields are displayed in the admin list view.
o Provides an at-a-glance overview of key information.
List Filter:
o Adds filters to the admin sidebar.
o Allows for quick data filtering based on field values.
Ordering:
o Defines the default order of records in the list view.
o
Permissions:
 Manages user access to different parts of the admin
interface.
 Ensures data security and role-based access control.
Read-Only Fields:
 Specifies fields that should be read-only in the form
view.
 Prevents modification of certain data by users.
Customizing the Admin Interface for the Book Model in Django

How These Changes Improve the Admin Interface


 Enhanced Usability: By displaying multiple columns (title,
publisher, publication_date), users can quickly scan important
information without opening each record.
 Efficient Filtering: The filter bar allows users to slice the
dataset by publisher and publication_date, making it manageable
even with a large number of books.
 Logical Ordering: Displaying the most recently published
books first ensures that the latest information is readily
accessible.
 Quick Search: The search functionality saves time by allowing
users to find books by title efficiently.
When and Why to Use the Admin Interface

•Data Entry Efficiency:


•Ideal for handling data entry tasks, especially useful for nontechnical users.
•Originally designed to facilitate content entry by reporters and developers simultaneously.
•Nontechnical User Access:
•Allows nontechnical users to enter and manage data easily.
•Simplifies collaboration between content producers and developers.
•Inspecting Data Models:
•Useful for inspecting newly defined models and entering dummy data.
•Helps identify and correct data modeling mistakes quickly through a graphical interface.
•Managing Acquired Data:
•Effective for editing and managing data that is automatically acquired.
•Provides an easy way to address issues with automatically sourced data.
•Development Workflow:
•Supports a streamlined development workflow by separating content entry and interface
development.
•Allows developers to focus on creating the public-facing interface while content producers
handle data entry.

You might also like