Fullsatck
Fullsatck
Full-stack development
• Django (Python)
• Flask(Python)
• Ruby on Rails (Ruby)
• Express.js (JavaScript/Node.js)
• ASP.NET Core (C#)
• Django (Python): Django is a high-level web framework for Python
that follows the MVC pattern. It provides a robust set of features for
building web applications, including an ORM, URL routing, form
handling, session management, and a built-in admin interface.
• pip is the package installer for Python. It's a command-line tool that
allows you to install, manage, and uninstall Python packages from the
Python Package Index (PyPI) .
How to install Django in python
Open command prompt and type:
pip install django
Check installed Django in python
Creating new project in Django
• Use below command to create Django project
django-admin startproject project
• Our view function returns an HTML page that includes the string
"Welcome to Django" . But how do we tell Django to use this code?
That’s where URLconfs come in.
• A URLconf is like a table of contents for your Django-powered Web
site. Basically, it’s a mapping between URL patterns and the view
functions that should be called for those URL patterns.
Views to display current time
How Django Processes a Request
•.
1. When a browser makes an HTTP request, a server handler creates the
HttpRequest.
2. The handler manages the flow of the response processing.
3. Request or View middleware is called to enhance HttpRequest objects or
handle specific requests.
4. If middleware returns an HttpResponse, the view is bypassed.
5. Bugs are common, but exception middleware can help manage them.
6. If a view function raises an exception, control goes to the exception
middleware.
7. The exception middleware can handle the error or re-raise it if no
HttpResponse is returned.
8. Django provides default views for friendly 404 and 500 error responses.
9. Response middleware is used to process HttpResponse before sending it to
the browser.
10. Response middleware also helps in cleaning up request-specific resources.
URLconfs and Loose Coupling
• This detailed error page contains sensitive information that is useful for
developers but should not be exposed to the public. If your website is live
on the internet, you wouldn't want visitors to see this technical
information, as it could potentially be used to exploit your site. Therefore,
Django only shows this detailed 404 error page when the project is in
debug mode, which is meant for development purposes.
Passing Values Through the URL in Django
• Let’s create a second view that displays the current date and time offset
by a certain number of hours.
• If, all of a sudden, we wanted to create a page that displayed the time five hours into the future, we’d have to create a
separate view and URLconf line for that, furthering the duplication and insanity. We need to do some abstraction here.
• Instead we create one view function as shown below to avoid redundancy, and to enhance the performance .
The view function, hours_ahead, takes two parameters: request and offset.
• request is an HttpRequest object
offset is the string captured by the parentheses in the URLpattern.
For example:
If the requested URL is /time/plus/3/, then the offset would be the string '3'.
If the requested URL is /time/plus/21/, then the offset would be the string '21'.
When the offset value is 3, the view function will display the current time with an additional 3 hours. Similarly, if the offset
value is 21, the view function will display the current time with an additional 21 hours.
• Now that we’ve designated a wildcard for the URL, we need a way of passing that data to the view
function, so that we can use a single view function for any arbitrary hour offset.
• re_path: This function allows you to define URL patterns using regular
expressions. It's useful for more complex patterns.
• Regular Expression: r'^time/plus/(?P<offset>\d{1,3})/$'
• ^time/plus/: Matches the beginning of the URL with the literal string 'time/plus/'.
• (?P<offset>\d{1,3}): Captures one to three digits as a named group called 'offset'.
• $: Indicates the end of the URL.
• hours_ahead: This is the view function that will handle the logic for
displaying the current time plus the specified number of hours.
• Now that we’ve designated a wildcard for the URL, we need a way of passing that data to the view
function, so that we can use a single view function for any arbitrary hour offset.
Django’s Pretty Error Pages
you'll see an error page with a significant amount of information, including a TypeError message
displayed at the very top: "unsupported type for timedelta hours component: str".
Django’s Pretty Error Pages
• At the top of the page, you get key information about the exception, including its type, any associated
message (like "unsupported type"), the file where it occurred, and the line number of the error.
• Below the exception information, the page shows the full Python traceback. This is like the standard Python
traceback but more interactive. For each step in the stack, it shows the file name, function/method name,
line number, and the source code of that line.
• Clicking on the source code line (shown in dark gray) reveals several lines of code before and after the error
for context. Clicking "Local vars" under any frame displays a table of local variables and their values at the
time of the exception, which is very helpful for debugging.
• Under the "Traceback" header, there's an option to switch to a "copy-and-paste view." This version of the
traceback can be easily copied and shared, useful for getting help from others, like in the Django IRC chat
room or on the Django users mailing list.
• The “Request information” section provides detailed information about the web request that caused the
error, including GET and POST data, cookie values, and meta-information like CGI headers. Appendix H
contains a complete reference of all the data a request object holds.
Questions
Module-2: Django Templates and Models
Template System Basics
print (t)
• This line prints the representation of the template object t to the console.
Multiple Contexts, Same Template
1. Create the folder templates in your project.(My project is newpgm1)
if/else tag:
The {% if %} tag evaluates a variable, and if that variable is “true”, the system will
display everything between {% if %} and {% endif %}.
Syntax:
if tag if-else tag else-if ladder tag
in operator - To check if a certain item is present in an object.
• Author: Fields include salutation, first name, last name, email, and optional headshot
photo.
• Publisher: Fields include name, street address, city, state/province, country, and website.
• Book: Fields include title, publication date, many-to-many relationship with authors, and
a foreign key relationship with a single publisher.
The first step in using this database layout with Django is to express it as Python code. In
the models.py file that was created by the startapp command, enter the following:
Publisher Model SQL structure
Author Model Book Model
• In Django, each database model is represented as a Python class that
inherits from django.db.models.Model. This parent class provides all the
functionality needed to interact with a database.
• Therefore, our models focus only on defining their fields using a
straightforward and concise syntax
• SQL query
Filtering Data
• Most of the time, we don't need all the data from a database table,
we only need specific records.
• The filter() method in Django takes keyword arguments that specify the conditions for the
data you want to retrieve. These arguments are translated into SQL WHERE clauses to filter
the data in the database.
Lets learn how below SQL query can be implement using Django:
• Out-put:
• This line retrieves all Publisher records from the database where the
name of the publisher is "Apress Publishing".
• It translates to an SQL WHERE query that looks like:
SQL AND clauses
• You can pass multiple arguments into the filter() method to further narrow
down your query results. When you provide multiple conditions, they are
combined using SQL AND clauses.
• This query retrieves all Publisher records where the country is "U.S.A." and the state_province is "CA"
SQL LIKE Statement
• By default, Django's filter() method uses the SQL = operator for exact match lookups.
• Django offers other lookup types for different kinds of searches.
• The get() method is used to fetch a single object from the database.
• Raises an exception if multiple objects are found, because it’s designed to return only one.
• A query that doesn't find any objects will also cause an exception.
Ordering Data
• all()- Getting back data in some arbitrary order chosen by the database
• order_by("name") - Method is used in Django to sort query results based on a specified
field.
• We can also specify reverse ordering by prefixing the field name with a –
(a minus sign character):
Chaining Lookups
• Combining Filtering and Ordering in Django is called Chaining Lookups.
• You can filter and order data by chaining lookups together.
• This line filters the Publisher objects to include only those from the U.S.A. and then
orders these results by name in descending order
Slicing Data
• Another common need is to look up only a fixed number of rows. Imagine you
have thousands of publishers in your database, but you want to display only the
first one or only few rows. You can do this using Python’s standard list slicing
syntax:
• Fetch the Publisher object named "Addison-Wesley" using the get() method, then call the delete() method
on it to remove it from the database.
Making Changes to a Database Schema
When using the syncdb command (now replaced by migrate in newer versions of Django), it only
creates new tables and doesn't apply changes to existing models or delete models. If you modify
a model's field or delete a model, you need to manually update the database. Here's how to
handle schema changes and important points to remember:
2.Field Mismatch: Django will throw an error if a model has a field not present in the
database table when you try to query it.
3.Extra Columns: Django doesn't care if the database table has columns not defined in
the model.
4.Extra Tables: Django doesn't care if there are database tables without corresponding
models.
Module No- 3
The Django Administration Site
• If you didn't create a superuser when you first ran `syncdb`, you'll need to
create one by running `django/contrib/auth/bin/create_superuser.py` so
you can log in to the admin interface.
Step 3:Add the admin URL pattern
• Add the URL pattern to your urls.py.
• URL patterns should look like the following:
How to crate superuser of Admin
• Run this to create superuser command:
• In this example, we've defined a Contact model with three fields: name, email,
and message.
• We've also defined a form (model form) ContactForm that is tied to the Contact model
• When a user submits the form, you can save the data to the database using
the form.save() method:
• In this example, when the form is valid, we call the form.save() method to save the data
to the database.
• The save() method will create a new Contact instance with the form data and save it
from django.shortcuts import render, redirect
• render is a shortcut function that renders a template with a given context.
• redirect is a shortcut function that redirects the user to a different URL.
{% csrf_token %}
• This is a Django template tag that generates a CSRF (Cross-Site Request
Forgery) token.
• This token is used to prevent CSRF attacks by verifying that the form
submission comes from the same origin as the form
URLConf Ticks
•Simplicity: Easy to read and understand, as each URL •Scalability: Can become cumbersome with many view
pattern is clearly mapped to a specific view function. functions, leading to a long list of imports.
•Direct Access: Directly importing the view functions •Potential for Circular Imports: If view functions need to
allows for straightforward referencing. import something from urls.py, it can lead to circular import issues.
Importing the Entire Views Module
• Instead of importing each view function individually, you import the
entire views module and then reference the view functions using the
module.
•Organization: Keeps the urls.py file cleaner with a •Less Explicit: Less immediately clear which
single import statement for all views. specific view functions are used without looking at
•Avoids Circular Imports: Reduces the risk of circular the module itself.
imports because only the module is imported, not individual •Verbose: Requires fully qualified names
functions. (views.home), which can be slightly more
verbose.
Using String References to View Functions
• You can reference view functions as strings, which can be useful for
avoiding circular import issues. Django will resolve these strings to the
actual view functions.
•You can return non-HTML content by setting the MIME type in the
HttpResponse class.
•The MIME type (content_type) tells the browser what type of content is
being returned (e.g., an image, a PDF, etc.).
• MIME: Multipurpose Internet Mail Extensions.
• content_type="image/png": This part of the HttpResponse tells the browser
that the content being returned is a PNG image. The content_type
parameter specifies the MIME type of the response.
Common MIME Types
• A simple example of a view that returns a PNG image
• The open() function reads the image file from the disk.
• HttpResponse is used to return the image data with the MIME type
image/png.
• The open() function is used to open the image file located
at "/path/to/my/image.png".
Installing ReportLab
Writing Your View
Complex PDFs .
Installing ReportLab
Linux Users:
•Check Package Management: Many modern Linux distributions include
ReportLab in their package repositories.
•Ubuntu Example: Install using apt-get install python-reportlab.
• Test Installation:
• Open the Python interactive interpreter and run
>>> import reportlab
• If no errors are raised, the installation was successful.
Writing Your View (creating Simple PDF)
• Generating PDFs dynamically with Django is straightforward using the ReportLab API, which acts on file-like
objects. Here's an example of a "Hello World" PDF generator:
• response = HttpResponse(content_type='application/pdf'):
Creates an HttpResponse object with the content_type set to 'application/pdf'. This
tells the browser that the response is a PDF file.
• response['Content-Disposition'] = 'attachment; filename=hello.pdf':
Sets the Content-Disposition header to attachment; filename=hello.pdf. This instructs the browser to
prompt the user to download the file as hello.pdf.
• p = canvas.Canvas(response):
Creates a Canvas object from ReportLab, using the response object as the "file." The Canvas class
expects a file-like object, and HttpResponse fits this requirement.
• p.drawString(100, 100, "Hello world."):
Uses the drawString method of the Canvas object to draw the string "Hello world." at the coordinates
(100, 100) on the PDF.
• p.showPage(): Finalizes the current page. If you have multiple pages, this method saves
the current page and starts a new one.
• p.save(): Saves the PDF document. This is crucial to ensure the PDF file is properly closed
and not corrupted.
Complex PDFs
• When you're creating a complex PDF document (or any large data
file), it's a good idea to use the cStringIO library.
• This library lets you create a file-like object that you can write to, just like a
regular file.
• The advantage is that cStringIO is very fast because it's written in the C
programming language.
• By using cStringIO, you can create the PDF in memory without having to save
it to disk first. Once the PDF is complete, you can then send it directly to the
user as a response.
Here’s the previous “Hello World” example rewritten to use cStringIO:
The Syndication Feed Framework
· The line instructs Django to use the RSS framework for handling all URLs starting with
"feeds/".
· The "feeds/" prefix can be customized to fit specific needs.
· The URLconf line includes an extra argument: {'feed_dict': feeds}.
· This extra argument is used to pass the syndication framework the feeds to be published
under the URL.
· The feed_dict can be defined within the URLconf itself.
• URL Configuration:
• These attributes set the title, link, and description of the feed.
• This method returns the latest 5 entries of the given category, ordered by their publication date in
descending order.
• This method returns the content of a given entry.
• This method returns the URL for a given entry's detail view, reversing the URL
pattern named entry-detail with the entry's primary key as an argument.
Key Components of the Feed Class:
Simple feed of LatestEntriesByCategory
A More Complex Feed
•Some developers prefer to offer both Atom and RSS versions of their feeds.
•This is easily achievable in Django.
1. Create a subclass of your feed class.
2. Set the feed_type to the desired format (e.g., Atom).
3. Update your URLconf to include the additional versions.
Updated urls
The Sitemap Framework
o rk
mew
p Fra le
te ma xamp
Si E
Installation
Initialization
To activate sitemap generation on your Django site, add this line to your URLconf:
(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
Sitemap Classes
• Purpose: Simplifies creating views that display lists and details of database objects.
• Benefits: Reduces repetitive code, leverages built-in Django functionality for common tasks
• This example demonstrates how to use Django's generic views to create a list page for all
publishers.
URL Configuration:
Publisher Model:
• list_detail.object_list:
• This is the view function that will be called when the URL is matched.
• list_detail is a module in Django that provides generic views for displaying
lists of objects.
• object_list is a specific view function within that module that displays a list of
objects
• publisher_info: This is an optional argument that is passed to the
view function. In this case, it's likely a dictionary that contains
information about the publishers objects.
Template Example:
Extending Generic Views
• Using generic views can save you a lot of time when building a website.
But sometimes, they're not enough. You might need to do something
that generic views can't do.
• We can make it clearer by giving the variable a more descriptive name, like publisher_list or
publisher. This way, it's obvious that the variable contains a list of publishers .
• We can change the name of the variable by using an argument called template_object_name.
This argument tells Django what name to use for the variable in the template .
Making “Friendly” Template Contexts
"queryset" : Publisher.objects.all(): This line tells Django to retrieve all objects from Publisher model
and store them in a variable called queryset
"template_object_name" : "publisher": This line tells Django to use the variable name publisher when
rendering the template. This means that in the template, you can access the publisher objects using the
variable publisher.
Adding Extra Context
• When you need to add extra information to a template beyond what a generic view
provides, you can use the extra_context parameter. This parameter allows you to pass
additional data to the template.
• For instance, if you want to show a list of all publishers on a publisher detail page, you can
use extra_context like this:
• This will create a variable {{ publisher_list }} in the template that holds the list of all publishers.
• The Problem:
The query Publisher.objects.all() is only evaluated once, when the URLconf is loaded.
This means that if you add or remove publishers, the webpage won't show the changes until you restart the web server.
• The solution is to use a callback in extra_context instead of a value.
• Any callable (i.e., a function) that’s passed to extra_context will be
evaluated when the view is rendered (instead of only once). You could do
this with an explicitly defined function:
Viewing Subsets of Objects
• This tells the view to show all books, but in the order
of their publication date.
• What if we want to show only books published by a specific publisher,
like Apress Publishing, We can use a queryset with a filter:
This tells the view to show only books published by Apress Publishing,
and to use a custom template called apress_list.html
Complex Filtering with Wrapper Functions