Professional Documents
Culture Documents
Creational design patterns concern the process of object creation. These are
the patterns comes under creational design patterns.
Intent
Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.
Problem
Instantiation of families of related objects.
Where it is applicable?
We have to create set of objects which are going to work together.
Supporting different families like system, OS or different versions of
product.
Creation of products has to be separated from use.
Interface has to be provided to outside world; and there is a need to
hide implementation like in case of libraries, frameworks, plug-ins.
Structure
Participant classes
AbstractFactory provides interface for creating product objects.
ConcreteFactory classes derived from the AbstractFactory
implements the methods for creating product objects. Each concrete
class represents one family, so we can say ConcreteFactory1 has the
methods to create objects for Series 1 product objects and
ConcreteFactory2 has the methods to create objects for Series 2
product objects.
AbstractProduct classes provides interface for operations on
Products.
Product classes are concrete classes derived from AbstractProduct
classes to implement the methods for Product.
Client uses the Factory and Product.
Example
We want to create set of objects to manage the system. The families are
Unisys and IBM.
Intent
Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
Problem
A class has to instantiate subclass of another class but does not know
which one.
Solution
Redefine a method in derived class which will decide which subclass to
instantiate.
Where it is applicable?
Framework and Libraries
A class does not know the object it has to instantiate or it wants the
objects to be created by its subclass.
Parallel class hierarchies
Structure
Participant classes
Product class provides the interface for object to be created by
method FactoryMethod().
ConcreteProduct is derived from Product and implements the
interface.
Creator class has abstract method FactoryMethod(). It also has
method AnOperation() which uses FactoryMethod().
ConcreteCreator is derived from Creator and implements the
FactoryMethod().
Example
We have framework of IDE and we want to add the support for Unisys project
and IBM project.
UnisysProject and IBMProject classes are derived from abstract class
Project.
Suppose the ProjectCreator class wants to create new project which is
object of UnisysProject. It has abstract method CreateProject() which is
implemented in derived class UnisysProjectCreator. It calls
CreateProject() method in NewProject(), so CreateProject() method of
class UnisysProjectCreator instantiates the object of class
UnisysProject and returns it to NewProject().
So we can see the subclass has instantiated the object which was
known later only.
Intent
Separate the construction of a complex object from its representation
so that the same construction process can create different
representations.
The intent is to separate the construction process of complex object and its
different representation uses the same construction process.
Problem
Construction of complex object which requires different
representations.
Sometime complex object requires to be created in steps and then comes the
final object, so it's like creating component and assembling it into final
product. Also sometime it is required to have different representation, so
different components are required for assembling of a particular product.
Solution
Come up with way to create complex object in steps.
Construction process should be separated from representation of
object.
Provide the way for different representation of object.
Where it is applicable?
A complex object has to be created in steps.
Same construction process of object is required to provide different
representation of final object.
The construction process requires separation from representation.
Structure
Participant classes
Builder provides interface for creating parts of object.
ConcreteBuilder class is derived from Builder and implements the
methods of Builder for creating parts of object. This assembles the part
to make a final product. It has the representation of objects and
provides the interface to get the created object.
Director class has Builder as aggregation, it uses builder interface for
constructing the object.
Product represents object to be created.
How they work together?
Client uses the Director and provides the information for the product it
wants to create. Director has construction logic based on the provided
information, and uses builder interface to create parts of object,
concrete builder methods create the part of the object and assemble
them for a required product. The builder provides the product to
Director through its interface.
So you can see construction process is separated from representation
of object. The internal structure of object is not known to the outside
world as it is with concrete builder only.
The construction process has a way to create object in parts and well
managed by Director.
New representation of object will require adding new concrete builder
which can be easily added. Also it will be easy to modify the
construction logic and representation of objects.
Some scenarios may require access of intermediate object and has to
be taken care through builder. You can see, there is no interface for
product as final objects will be quite different and also well known to
client as it provides the input.
Builder has all the methods for creating parts of objects, so the
required ones have to be implemented in concrete builder.
Intent
Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype.
Problem
Framework needs to instantiate application specific objects.
Solution
Application can use the cloning of instance for subclasses.
We can have a prototype instance which is used to get abstract behavior of
Prototype and clone the objects of subclasses.
Where it is applicable?
Framework to be used by developer
To avoid parallel hierarchies.
Wherever it is good to have a prototype and clone it, instead of creating
a new object every time.
Structure
Participant classes
Prototype class has abstract method Clone(). It provides interface for
cloning the object.
ConcretePrototype classes are derived from Prototype and
implements the Clone() method. These classes clone their respective
object and returns it to client.
Client has the prototype instance and uses its interface for cloning.
Intent
Ensure a class only has one instance, and provide a global point of
access to it.
The intent is to have only one instance of a class and it should be accessible
to multiple clients through well-defined access point.
Problem
Application requires only one instance of the class and that instance of
class should be accessible to multiple clients.
There are scenarios where one and only one instance of class is required, for
example File System, System Manager etc and it has to be accessed from
multiple applications. Introducing of global variable provides access to
multiple applications but does not make sure that there will be only one
instance.
Solution
Make sure only one instance of class is created and the same one is
accessible to multiple clients.
The class itself can take the responsibility of creation of not more than one
instance and can provide the well-defined access point for multiple
applications.
Where it is applicable?
One and only one instance of a class is required and well-defined
access point is provided to access it by multiple applications.
Structure
Participant classes
Singleton class has method Instance() which has responsibility to
create single instance and is access point for providing the instance to
multiple applications. The class has data member uniqueInstance
which keeps the instance information.
Intent
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that could not otherwise because of
incompatible interfaces.
The intent is to convert the interface of existing class to the one which client is
expecting.
Problem
Want to use existing system/component but the current system used
by client does not have interfaces that are compatible with existing one.
The client has the interface that he wants to use, we have an existing class
which can be reused but it has different interface. So either a new class is
required or we have to find a way to use the existing one.
Solution
Come up with a class which adapts the interface of existing
system/component to the new one which client expects.
The system will adapt the existing interface and will provide it in the way client
expects.
Where it is applicable?
There is an existing class which we want to use in a system and may
require to provide interface in the way applicable for the system. Or we
can say we want to reuse the class but we don't have compatible
interfaces.
Structure
Composition
Participant Classes
Target class provides interfaces to clients and has abstract method
Request().
Adapter class is derived from Target class and implements the method
Request().
Adaptee has the functionality we want to reuse.
Structure
Inheritance
Participant Classes
Target class provides interfaces to clients and has abstract method
Request().
Adapter class is derived from Target and Adaptee. It implements the
method Request() and inherits the functionality of Adaptee.
Adaptee has the functionality we want to reuse.
Example
We want to reuse already available class for HP System operations.
OperationManager class provides the interface ShutDown() to client.
Concrete class HPOperationManager implements the method ShutDown().
The class HPOPSystem already exists and provides the functionality through
its method PowerOff(). HPOperationManager has instance of HPOPSystem
and uses it in ShutDown() method to call the method PowerOff().
Intent
Decouple an abstraction from its implementation so that the two can
vary independently.
Problem
Implementation classes derived from abstract class makes difficult to
modify, extend and adding of new implementation classes.
When we use inheritance for abstraction class and implementation class then
the abstraction binds with implementation. This makes it complex to further
modify and extend. Also as more implementation classes are required with
variation, then it becomes complex to add more and more in same hierarchy
as the variation may come in different forms – like OS, system etc.
Solution
Come up with interfaces for implementation.
Derive the implementation classes from abstract implementation class.
Use the interfaces of implementation in concrete class of abstract
class.
So the abstraction and implementation will be independent and will have their
own hierarchy.
Where it is applicable?
Binding between abstraction and implementation has to be avoided.
To reduce further subclassing by making abstraction and
implementation in separate hierarchy.
Structure
Participant classes
Abstraction class provides the interface to the client and has the
instance of Implementor class.
RefinedAbstraction class is derived from Abstraction class and
implements the interfaces.
Implementor class has the interfaces implemented by implementation
classes.
ConcreteImplementorA and ConcreteImplementorB classes
implements the methods of Implementor class.
Intent
Compose objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects and
compositions of objects uniformly.
Problem
The primitive and composite objects have to be handled differently. To
distinguish these objects for manipulation increases the complexity.
Solution
Come up with a way to manipulate the primitive and composite object
uniformly.
That means both the primitive and composite object have to be handled in
similar manner.
Where it is applicable?
When part-whole hierarchy of object has to be represented.
Wherever primitive and composite objects have to be handled in similar
manner.
Directories and Files in File system are the best example.
Structure
This is the UML structure of Composite design pattern-
Participant classes
Component class provides the interface Operation().
Concrete classes Leaf and Composite implements the method
Operation().
Intent
Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality.
Problem
Need to add additional functionality to object. Subclassing makes it
inflexible and complex.
We may require to add some additional functionality to the object. This may
be done by using inheritance but that will make it static and inflexible and
client will not be able to add functionality as it is required.
Solution
Give the responsibility of adding additional functionality to another
object without using subclassing.
Where it is applicable?
Adding additional responsibility to an object dynamically.
To avoid subclassing for extending functionality.
Structure
Participant classes
Component class provides the interface to client for adding
functionality dynamically.
ConcreteComponent class represents the object where additional
functionality will be added.
Decorator class is derived from Component and has the responsibility
for adding additional functionality. It has instance of class Component.
The concrete
classes ConcreteDecoratorA and ConcreteDecoratorB are used for
adding functionality to the Component object.
Intent
Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem
easier to use.
Problem
It is difficult for client to use the subsystem with existing interfaces.
The client has to use multiple interfaces of different subsystem classes to use
the existing subsystem. This makes using the subsystem complex as the
number of interfaces grow.
Solution
Come up with a new simplified interface for client to use the system
easily.
The new simplified interface will use the existing subsystem interfaces. It will
be easy for client to use the new interface instead of using the multiple
subsystem interfaces and going into detail of knowing the existing subsystem
working and how the whole things are related.
Where it is applicable?
There are lot of subsystem classes and it is complex to use the
subsystem as there is lot of dependency within them. So simple
interface for client makes it easy to use.
Structure
Participant classes
Classes SybsystemClass1, SubsystemClass2 and SubsystemClas
s3 represent the existing complex subsystem which provides
functionality by using multiple interfaces.
FacadeSystem class provides new simple interface to client.
Intent
Provide a surrogate or placeholder for another object to control access
to it.
The intent is to provide a placeholder for another object and control its
access.
Problem
Need to defer the instantiation of object until it is required.
Sometimes object creation and initialization may be very costly affair and may
affect performance, so it is better to defer the instantiation until it is required.
Solution
Come up with another Proxy class which acts for real class and
instantiates the object of real class when required.
So we can have another class called proxy which will be placeholder for real
class and will instantiate the object of Real class when it is actually required.
Where it is applicable?
The cost of object instantiation is high.
Another object is required to present an object in different address
space called as remote proxy.
There is access control required for an object, called as protection
proxy.
Structure
Participant classes
Subject class provides the interface Request().
Proxy class works as place holder for RealSubject. It has instance of
class RealSubject, so it creates the object of RealSubject and uses the
method of RealSubject. It can instantiate when operation is required on
RealSubject; and can provide access control too on RealSubject
object. Proxy implements the interface which is provided by Subject.
RealSubject has actual functionality implementation of the interface
provided by Subject. Proxy presents as place holder for RealSubject.
Intent
Given a language, define a representation for its grammar along with
an interpreter that uses the representation to interpret sentences in the
language.
The intent is to define the grammar for a language and use the interpreter to
interpret the simple sentences of the language using this grammar.
Problem
A set of defined problem is coming again and again.
Solution
Define the problem in sentences of language and interpret these
sentences to solve the problem.
Where it is applicable?
A set of well-defined problem can be represented in simple sentences
of language. That means the grammar of language has to be simple,
otherwise parser tools are better alternative.
Structure
Participant classes
AbstractExpression class provides interface Interpret().
TerminalExpression class represents the terminal symbol in grammar
and implements method Interpret().
NonTerminalExpression class represents rule in the grammar and
will be there for every rule. This implements Interpret() method and
interprets every rule considering other rules.
Context class has the context information and will be used while
interpretation of Terminal and Non Terminal expressions.
Client has the representation of simple sentences of language with
defined grammar. This is in form of terminal and Non terminal
expressions.
Intent
Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm structure.
Problem
The algorithm has to be generic but some steps are require to be
defined by user.
There may be a situation where steps of algorithm are not known. For
example, the framework has some steps of algorithm which are supposed to
be provided by user. There may be many scenarios where some steps may
vary but the algorithm is generic.
Solution
Identify the invariant and variant part of the algorithm.
Have the implementation of invariant part in abstract class and variant
part in derived class.
So the algorithm structure is not changed and some steps are deferred to be
implemented by subclasses.
Where it is applicable?
The algorithm is generic with invariant and variant parts.
The variant parts are required to be deferred to derived class.
There is a need to provide extension points.
Structure
Participant classes
AbstractClass has method TemplateMethod() which defines a generic
algorithm. It also has abstract methods PrimitiveOperation1() and
PrimitiveOperation2(). These methods are variant parts of generic
algorithm().
ConcreteClass implements the abstract methods
PrimitiveOperation1() and PrimitiveOperation2().
Intent
Avoid coupling the sender of a request to its receiver by giving more
than one object a chance to handle the request. Chain the receiving
objects and pass the request along the chain until an object handles it.
The intent is to chain the receiving objects to handle the request one by one
till it gets handled.
Problem
Sender object does not know which object is going to handle the
request.
There may be a situation where the sender does not know which specific
object has to handle its request.
Solution
Have multiple objects to handle the request of sender object.
So we can have multiple objects in chain and handle the request one by one
till the request is handled.
Where it is applicable?
There may be multiple object which can handle the request.
The sender object does not know which object can handle its request.
Structure
Participant classes
Handler class provides interface HandleRequest() to client. It also has
member to keep the successor of handler object and method
MakeSuccessor() to set the successor.
The concrete
classes ConcreteHandler1 and ConcreteHandler2 implement the
method HandleRequest().
Intent
Encapsulate a request as an object, thereby letting you parameterize
clients with different requests, queue or log requests, and support
undoable operations.
Problem
It is required to issue the requests to objects. The requested operation
and the receiver is not known.
There are scenarios where the requested operation and receiver is not known
and only receiver knows what operation has to be done.
Solution
Come up with an object for requested operation, so that it can be
passed as any other object.
Where it is applicable?
The actions have to be performed but receiver and operation are not
known.
Undo operation is required to be supported.
Logging of actions are required to recover the system from crash using
logs.
There are different types of actions that have to be invoked in a similar
manner.
Structure
Participant classes
Command class provides interface Execute() to invoker.
ConcreteCommand class implements the method Execute() which
uses the receiver to carry out the operation. It has instance of class
Receiver.
Invoker class has the instance of class Command and invokes the
command interface to carry out the operation.
Receiver class has methods to do the operation for a request.
Intent
Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
The intent is to provide the access of aggregate object without exposing its
internal structure.
Problem
Need to access the elements of an aggregate object without exposing
the internal details of object.
Accessing elements of object is required with traversal, and at the same time
it should not expose the internal structure of aggregate object. Also this may
be applicable to different data structures, which provide different algorithms
for accessing and traversing.
Solution
Provide a way to access and traverse an aggregate object by giving
responsibility of access and traversal to another object.
So there can be common interface, which can be applicable for different data
structures to provide interface for accessing and traversing. There will be
separate objects having this interface and will have responsibility to access
the elements and traversal of aggregate objects.
Where it is applicable?
Access and traversal of aggregate object is required without exposing
its internal structure.
Common interface is required to access and traverse different data
structures.
Structure
Participant classes
Iterator class provides the interface for accessing the elements and
traversal of the aggregate object.
ConcreteIterator class implements the interface of Iterator class and
keeps track of current item of aggregate object.
Aggregate class provides the interface for creating Iterator object.
ConcreteAggregate class implements the method CreateIterator().
Intent
Define an object that encapsulates how a set of objects interact.
Mediator promotes loose coupling by keeping objects from referring to
each other explicitly, and it lets you vary their interaction independently.
Problem
There is too much communication between objects, which is increasing
the complexity and making it difficult to reuse the objects.
Solution
Encapsulate the behavior of interaction and coordination in a separate
object.
Where it is applicable?
There are set of objects with lot of interaction within them, thus
increasing the dependency.
It's becoming difficult to reuse the objects, because of too much
interaction and dependency.
Behavior has to be customizable without subclassing.
Structure
Participant classes
Mediator class provides interface for interaction between colleague
objects.
ConcreteMediator class implements the method and does the
coordination between colleague objects as required for behavior. This
has the instance of applicable colleague objects.
Colleague class provides interface for Colleague objects. It also has
the instance of Mediator object.
ConcreteColleague class implements the method and keeps the
instance of respective concrete mediator object.
Intent
Without violating encapsulation, capture and externalize an object’s
internal state so that the object can be restored to this state later.
Problem
Need to save state of an object to restore it later. Saving it externally is
difficult as it violates encapsulation.
There may be scenarios like undo, rollback, handling exceptions where object
has to be restored to previous state.
Solution
Store the state of the object in another object and make it accessible
from the object whose state is saved.
The object state will be saved in another object which will be created and
accessed by same object so it will not violate the encapsulation.
Where it is applicable?
An Exception has to be handled in a way where an object has to be
restored to its previous state.
The object state has to be stored somewhere to restore it later but
should not be accessed by anyone, other than the object whose state
is saved.
The scenarios of undo and rollback operations.
Structure
Participant classes
Originator class has the state to be captured. The method
CreateMemnto() is used to instantiate the Memento object which stores
the state of the originator object; and Method SetMemnto() is used to
get the previous state and restore the same.
Memento class keeps the internal state of the originator object and can
be accessed by originator only.
Caretaker class keeps the Memento object safely, this is nothing but a
mechanism for undo or rollback.
CodeIgniter Features
Let's see some of the features that make CodeIgniter great. The
following list is not exhaustive but gives you an idea of what to expect
when working with CodeIgniter.
Small footprint
Blazing fast
Users tend to favor applications that load very fast. If you have
worked with some of the modern frameworks, then you will realize
that they take less than one second to load just after installation.
CodeIgniter, you can loads on average around less than 50ms. The
extra time spent optimizing like is the case in another framework is
freed up when you are working with CodeIgniter framework.
21.8M
285
What is Linux Linux Beginner Tutorial
Loosely coupled
The built-in features are designed to work independently without relying too
much on other components. This makes it easy to maintain and make
upgrades
MVC Architecture
Excellent documentation:
The framework is well documented, and there are good books, tutorials and
answered forum questions on CodeIgniter. This means whatever challenge
that you have, chances are someone has already encountered the problem,
solved it and the solution is out there for you.
Extendable:
CodeIgniter comes with some libraries, and helpers out of the box. If what
you want is not there or you would like to implement an existing feature
your way. Then you can do so easily by creating your libraries, helpers,
packages, etc. You can also create REST API in CodeIgniter.
CodeIgniter is easy to master for anyone who is already familiar with PHP.
Within a very short time, the student can Learn CodeIgniter and start
developing professional applications using CodeIgniter.
For example, if you want to retrieve a customer with the id= 3, the controller
will receive your request, then request the CodeIgniter models to retrieve the
record with the id of 3. The CodeIgniter models will return the record to the
controller. The controller then forwards the result to the view which formats
it into a human-readable format. Then the results are returned to the user in
the browser.
Summary
CodeIgniter is a PHP framework for developing applications rapidly
The entire source code for CodeIgniter is close to 2MB. This makes it
easy to master CodeIgniter and how it works
The built-in features of CodeIgniter are designed to work
independently without relying too much on other components
The framework uses the Model-View-Controller architectural design
The framework is well documented, and they are good books,
tutorials and answered forum questions on CodeIgniter
CodeIgniter comes with some libraries, and helpers users out of the
box
CodeIgniter is easy to master for anyone who is already familiar with
PHP
In CodeIgniter user requests a resource, the controller responds first.
The controller understands the user request then request the necessary
data if it is important
Codeigniter 4 was released On February 24, 2020, the birthday of Jim
Parry, who was the project lead of Codeigniter 4 and died on January
15, 2020
Django introduction
Overview: Django
Next
In this first Django article, we answer the question "What is Django?" and give
you an overview of what makes this web framework special. We'll outline the
main features, including some of the advanced functionality that we won't have
time to cover in detail in this module. We'll also show you some of the main
building blocks of a Django application (although at this point you won't yet
have a development environment in which to test it).
What is Django?
Django is a high-level Python web framework that enables rapid development
of secure and maintainable websites. Built by experienced developers, Django
takes care of much of the hassle of web development, so you can focus on
writing your app without needing to reinvent the wheel. It is free and open
source, has a thriving and active community, great documentation, and
many options for free and paid-for support.
Complete
Django follows the "Batteries included" philosophy and provides
almost everything developers might want to do "out of the box".
Because everything you need is part of the one "product", it
all works seamlessly together, follows consistent design
principles, and has extensive and up-to-date documentation.
Versatile
Django can be (and has been) used to build almost any type of
website — from content management systems and wikis, through
to social networks and news sites. It can work with any
client-side framework, and can deliver content in almost any
format (including HTML, RSS feeds, JSON, XML, etc). The site
you are currently reading is built with Django!
Secure
Django helps developers avoid many common security mistakes by
providing a framework that has been engineered to "do the right
things" to protect the website automatically. For example,
Django provides a secure way to manage user accounts and
passwords, avoiding common mistakes like putting session
information in cookies where it is vulnerable (instead cookies
just contain a key, and the actual data is stored in the
database) or directly storing passwords rather than a password
hash.
Scalable
Django uses a component-based “shared-nothing” architecture
(each part of the architecture is independent of the others,
and can hence be replaced or changed if needed). Having
a clear separation between the different parts means that it
can scale for increased traffic by adding hardware at
any level: caching servers, database servers, or application
servers. Some of the busiest sites have successfully scaled
Django to meet their demands (e.g. Instagram and Disqus, to
name just two).
Maintainable
Django code is written using design principles and patterns
that encourage the creation of maintainable and reusable code.
In particular, it makes use of the Don't Repeat Yourself (DRY)
principle so there is no unnecessary duplication, reducing the
amount of code. Django also promotes the grouping of related
functionality into reusable "applications" and, at a lower
level, groups related code into modules (along the lines of
the Model View Controller (MVC) pattern).
Portable
Django is written in Python, which runs on many platforms. That
means that you are not tied to any particular server platform,
and can run your applications on many flavours of Linux,
Windows, and Mac OS X. Furthermore, Django is well-supported
by many web hosting providers, who often provide specific
infrastructure and documentation for hosting Django sites.
Note
Check out the release notes on the Django website to see what has changed
in recent versions, and how much work is going into making Django better.
Based on the number of high profile sites that use Django, the number of
people contributing to the codebase, and the number of people providing both
free and paid for support, then yes, Django is a popular framework!
Is Django opinionated?
Web frameworks often refer to themselves as "opinionated" or
"unopinionated".
Opinionated frameworks are those with opinions about the "right way" to
handle any particular task. They often support rapid development in a
particular domain (solving problems of a particular type) because the right way
to do anything is usually well-understood and well-documented. However they
can be less flexible at solving problems outside their main domain, and tend to
offer fewer choices for what components and approaches they can use.
Django web applications typically group the code that handles each of these
steps into separate files:
Note
The sections below will give you an idea of what these main parts of a Django
app look like (we'll go into more detail later on in the course, once we've set up
a development environment).
urlpatterns = [
path('admin/', admin.site.urls),
path('catalog/', include('catalog.urls')),
re_path(r'^([0-9]+)/$', views.best),]
Copy to Clipboard
The first argument to both methods is a route (pattern) that will be matched.
The path() method uses angle brackets to define parts of a URL that will be
captured and passed through to the view function as named arguments.
The re_path() function uses a flexible pattern matching approach known as a
regular expression. We'll talk about these in a later article!
The second argument is another function that will be called when the pattern is
matched. The notation views.book_detail indicates that the function is
called book_detail() and can be found in a module called views (i.e. inside
a file named views.py)
The example below shows a minimal view function index(), which could have
been called by our URL mapper in the previous section. Like all view functions
it receives an HttpRequest object as a parameter (request) and returns
an HttpResponse object. In this case we don't do anything with the request,
and our response returns a hard-coded string. We'll show you a request that
does something more interesting in a later section.
def index(request):
# Return HttpResponse
Copy to Clipboard
Note
The code snippet below shows a very simple Django model for a Team object.
The Team class is derived from the django class models.Model. It defines the
team name and team level as character fields and specifies a maximum
number of characters to be stored for each record. The team_level can be
one of several values, so we define it as a choice field and provide a mapping
between choices to be displayed and data to be stored, along with a default
value.
# filename: models.py
class Team(models.Model):
team_name = models.CharField(max_length=40)
TEAM_LEVELS = (
Copy to Clipboard
Note
The code snippet shows a view function (resource handler) for displaying all of
our U09 teams. The line in bold shows how we can use the model query API
to filter for all records where the team_level field has exactly the text 'U09'
(note how this criteria is passed to the filter() function as an argument, with
the field name and match type separated by a double
underscore: team_level__exact).
## filename: views.py
from django.shortcuts import renderfrom .models import Team
def index(request):
list_teams = Team.objects.filter(team_level__exact="U09")
Copy to Clipboard
## filename: best/templates/best/index.html
<meta charset="utf-8">
<title>Home page</title></head><body>
{% if youngest_teams %}
<ul>
{% endfor %}
</ul>
{% else %}
{% endif %}</body></html>