Django Important
Django Important
These
functions are so-called request handlers. In Django, a view is typically responsible for:
Most of the time, it’s made of code that connects to the database, manages user connections, and
also powers web applications or the API. The focus of back-end development code is more on
the business logic. It primarily focuses on how an application works and the functionality and
logic powering the application.
Adding a book (only for admin): This supposes that the client (front-end) should be able to
make a request to an API powered using whatever language is built for the back-end, containing
the data needed to create a new entry in the database that represents a book. This action is only
available to admins.
Listing all books: This supposes that the client should also be able to make a request to the API,
and this API should send as a response a list of all the books in JSON/XML format.
Just by taking a look at these two requirements, we can quickly understand that the front-end will
just be the interface through which to request these actions. However, the back-end will (taking
the first requirement as an example) make sure that the incoming request is possible (checking
for permissions such as whether the user making the request is really an admin) and that the data
in the request is valid – only after that can data be safely registered in the database.
Back-end developers use programming languages such as Python, to set up and configure the
server. These tools will allow them to store, process, and modify information. To make these
programming languages even more practical, developers will improve them with frameworks
such as Django. These tools will make development faster and more secure.
A back-end developer is therefore responsible for creating and managing all the elements
invisible to the end user. It is therefore they who are responsible for all the functionalities of the
site or the application. They are also responsible for creating the database which will allow,
among other things, the information provided by users to be retained. For example, the back-end
developer will use the databases to find the usernames and passwords that customers have used
to connect.
The back-end is typically made of three major parts:
Server: A machine or an application (NGINX) that receives requests
Application: A running application on the server that receives the requests, validates
these requests, and sends an appropriate response
Database: Used to store data
Thus, the responsibilities of back-end programmers could easily involve writing APIs, writing
code to interact with a database, creating modules or libraries, also working on business data and
architecture, and much more.
Coordinate and communicate with front-end developers to transfer data efficiently to the
client side of the application
Collaborate with quality assurance engineers to optimize the server-side processes and
also pass some security checks
Optimize the application when the number of requests or users scales as well
Analyze the requirements of the project and create a simple structure to handle bugs and
errors
Propose efficient solutions for cloud hosting but also build CI/CD pipelines
self.list() internally calls get_queryset(), which fetches the queryset from the
database.
REST requires less bandwidth and is more suitable for internet use. It is often preferred to the
more reliable Simple Object Access Protocol (SOAP) technology where the latter consumes
more bandwidth and highly complex. Also, API calls are not cached in SOAP. It is utilized to
obtain or provide data from an online service. The client can perform various operations by
utilizing the REST service. The major advantage of REST is that it is easier to document them
which can be referenced by developers to write programs. REST is a simple alternative to SOAP
and RPC, as it makes it easier to write the logic to access resources; resources here are
represented by a unique URL available with one request to this URL.
Cache-ability: When a Server sends a response to the client in its response it should indicate that
whether the response can be cached or not and for how much duration the responses can be
cached at the client side. This reduces network latency.
Uniform Interface: There are many different devices like smart phones, laptops, IoT devices,
etc. Each of these devices can act as a client. This constraint specifies that any device can interact
with the Server through the same uniform interface.
The client is a device which requests for resources. A server is a device which holds resources.
This constraint specifies that client and server should be separated. The principle used in this is
the principle of separation of concerns. Client does not know anything about the business logic.
The Server is not aware of the Client UI.
In the client - server architecture the client sends the date along with the associated data to the
server. The server verifies the information provided in the meta data including parameters
passed in the Request Headers. The server checks if the client is authorized to receive the
information. If yes, the server processes the request and returns a HTTP response in the
prescribed format to the client along with Status Code.
For your beacon-based marketing system, backend validations are critical to ensuring data
integrity, security, and business logic enforcement. These validations should be applied at
three key backend layers:
1. Model-Level Validations (Database constraints)
2. Serializer-Level Validations (API request validation)
3. View-Level & Middleware Validations (Authentication, rate limiting, etc.)
You should apply validations at multiple layers to ensure security, data consistency, and
correctness.
Layer Purpose
Middleware & Global Validations Adds security layers like authentication, rate limiting, and logging.
Model-Level Validations
These are database-level validations enforced by Django models.
A beacon is a small device broadcasting signals for advertisements. Each beacon should have:
Django’s automatic admin interface offers the functionality of adding, editing, and deleting
items within a database in a graphical, user-friendly way. Django organizes your website into
apps an app represents one component of a website. Models store data for your app key for
making dynamic websites!
In a web app built with Python (by using any framework), your Python files always run on the
web host's server and are never transmitted to a user's computer. Other files like CSS and
JavaScript are used only by the browser, so the host server simply delivers them as-is when
they're requested. These types of files are referred to as "static" files, and Django can deliver
them automatically without you needing to write any code.
Book.objects.all()
Purpose: Retrieves all records from the Book model as queryset objects.
Return Type: Returns a queryset of full model instances (each entry is an instance of the Book
model).
Usage: Allows access to all the fields and methods defined in the model, providing full
functionality of the model instance.
Book.objects.values()
Purpose: Retrieves all records but returns them as dictionaries of field-value pairs.
Return Type: Returns a queryset of dictionaries (each entry is a dictionary with keys as field
names and values as field data).
Usage: Useful when you only need raw field data without creating full model instances. It's more
lightweight than all() since it doesn't instantiate model objects.
No, PostgreSQL itself is not installed via a requirements.txt file because it is a database
server and not a Python package. The requirements.txt file is typically used for managing
Python dependencies in a virtual environment using pip.
However, you can include a Python package for interacting with PostgreSQL, such as psycopg2,
in your requirements.txt. For example:
psycopg2==2.9.7
sudo apt update && sudo apt upgrade -y
By default, PostgreSQL creates a user named postgres. Switch to this user to access
PostgreSQL’s command-line interface:
sudo -i -u postgres
Psql
\q
Once it’s done, we’ll install a PostgreSQL adapter for Python, psycop
Django==4.0
psycopg2_binary
Great – now that we have the adapter installed, let’s quickly create the database we’ll use for this
project.
For that, we need to connect as a Postgres user in the terminal and then access the psql terminal.
In that terminal, we can enter SQL commands.
For Linux users, you can log in as follows:
sudo su postgres
Then, enter psql.
We are nearly done. We also need to make sure this user can create a database. This will be
helpful when we can run tests. To run tests, Django will configure a full environment but will
also use a database:
ALTER USER core CREATEDB;
an API will help facilitate interaction between our Django backend, and our frontend JS code.
For example, imagine that we want to create a frontend application that allows users to add new
books to the Bookr database. The user's web browser would send a message (an HTTP request)
to our API to say that they want to create an entry for a new book, and perhaps include some
details about the book in that message. Our server would send back a response to report on
whether the book was successfully added or not. The web browser would then be able to display
to the user the outcome of their action.
Serializer converts data models and complex queries from the database into types understandable
by frontend frameworks, such as JSON or XML.
View sets: To make a view function appear in a browsable API from the Django REST
framework, it needs to have @api_view () decorator, which takes a list of allowed http methods
as an argument.
A metaphor for API is a waiter/waitress, who can understand different customers' orders. They
will then act as a middleman between the customers and the chefs in the kitchen. If you were the
boss of the restaurant, the key benefit of having a waiter/waitress here between your customer
and the kitchen is that the customers will be shielded from seeing your business secrets. They
don't need to know how the meal is prepared. They just need to send an order through the
waiter/waitress, and they will get the meal they ordered. Similarly, in computer science, one of
the key benefits of having API is encapsulation. We encapsulate the logic so that people
outside won't be able to see it. With this arrangement, big companies with sensitive information
are willing to provide services to the world through APIs, confident that their internal
information won't be revealed.
REST Constraints/Principles
Client-server: There is an interface between the client and the server. The client and
server communicate through this interface and are independent of each other. Either side
can be replaced as long as the interface stays the same. Requests always come from the
client-side.
Stateless: There is no concept of state for a request. Every request is considered to be
independent and complete. There is no dependence on the previous request nor
dependence on a session to maintain the connection status.
Layered system: There can be multiple layers in the system, and the goal here is to hide
the actual logic/resources. These layers can perform different functions, such as caching
and encryption.
Uniform interface: The interface stays the same. This helps to decouple the client and
server logic.
I know the encapsulation concept from OOP which is hiding the implementation detail and data
inside a class and provide public/setter getters to manipulate the data indirectly and I found it
similar conceptually with API. An API also hides the logic and provides an endpoint which are
similar with public setter / getters I am right?
Yes, you're absolutely correct! The concept of encapsulation in OOP and the functionality of
APIs share similarities in their approach to exposing and managing access to functionality or
data. Let’s break it down:
An API (Application Programming Interface) provides a set of endpoints (publicly accessible
functions or methods) that allow interaction with the system or service while hiding its internal
logic or data.
Purpose:
Abstracts and hides complex implementation details.
Provides controlled access to system resources or logic via endpoints.
Ensures consistency and security by defining what can and cannot be accessed.
Examples:
GET /api/account/balance # Retrieves the account balance
POST /api/account/deposit { "amount": 100 } # Deposits money into the account
Here, the internal workings of how the balance is stored or updated are hidden from the user. The
user interacts with well-defined API endpoints that ensure proper input validation and logic.
Clients knows what data is available through the API and can manipulate it, typically at the
request of a user. Logging-in with a username and password is one example of a technical
process known as authentication. When you authenticate with a server, you prove your identity
to the server by telling it information that only you know. Once the server knows who you are, it
can trust you and divulge the private data in your account. Basic Authentication is a perfectly
acceptable way for the server to authenticate the client in an API. Basic Auth only requires a
username and password. The client takes these two credentials, smooshes them together to form
a single value, and passes that along in the request in an HTTP header called Authorization.
When the server receives the request, it looks at the Authorization header and compares it to the
credentials it has stored. If the username and password match one of the users in the server's list,
the server fulfills the client's request as that user. If there is no match, the server returns a special
status code (401) to let the client know that authentication failed and the request is denied.
Though Basic Auth is a valid authentication scheme, the fact that it uses same username and
password to access the API and manage the account is not ideal. That is like a hotel handing a
guest the keys to the whole building rather than to a room. Mine: Django has its own
authentication so DRF should also have its own. API Key authentication is a technique that
overcomes the weakness of using shared credentials by requiring the API to be accessed with a
unique key. In this scheme, the key is usually a long series of letters and numbers that is distinct
from the account owner's login password. The owner gives the key to the client, very much like a
hotel gives a guest a key to a single room.
In web programming, the API is comprised of a collection of URLs that can be used to make
remotely executing functions appear to run locally. When we make API calls like /factor.py?
number=14728, we are invoking a remotely implemented function called factor.py. factor.py
expects its arguments to be expressed within the query string (here, one argument called
number). The factorization is returned via the response payload. we need to define the structure
and behavior of a number of endpoints allowing us to synchronize application state between
client and server. E.g.
GET /scripts/getListItems.py, which returns a JSON object of item-id/item-text pairs.
POST /scripts/addListItem.py, which posts the text of a new item so it’s shared with
and stored by the server.
POST /scripts/removeListItems.py, which posts a JSON list of item-ids that the server
should delete.
In the multiple page application in Django without using API can the internal information can
reveal
Yes, in a Multiple Page Application (MPA) built using Django without APIs, internal
information can be unintentionally exposed if not handled securely. Here's how this can
happen and how to prevent it:
3. CSRF Vulnerabilities:
o Without proper CSRF protection, attackers could exploit forms or endpoints to
perform unintended actions on behalf of a logged-in user.
5. Query Parameters:
o Sensitive data passed through query strings (e.g., ?user_id=123) can be exposed to
browser history, logs, or third-party trackers.
Mitigation Strategies
1. Access Control:
o Use Django's built-in authentication and authorization system (@login_required and
permission checks) to restrict access to views and data.
2. Secure Templates:
o Only include the data necessary for rendering the page.
o Avoid passing sensitive data directly to templates.
3. CSRF Protection:
o Ensure that all forms include the {% csrf_token %} tag.
o Use Django’s middleware for CSRF protection.
5. Debugging Information:
o Set DEBUG = False in the production environment.
o Use proper logging and avoid exposing stack traces or debugging details in error
messages.
Conclusion
While APIs are often used to structure and secure data communication, an MPA without APIs
can still be secure if you implement proper access control, sanitize data, and follow security best
practices. However, APIs often add an additional layer of abstraction and security to minimize
such risks.