Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

Module -3

Django Admin Interfaces and Model Forms


Admin Interface comments
• crucial part of many websites, allowing trusted
administrators to manage site content through
a web-based platform.

• Examples include blog posting interfaces,


comment moderation tools, and content
management systems for updating site
information.
Overview
• Django's automatic admin interface, detailing
how to activate, use, and customize it to fit
specific needs.

• With Django's approach, developers can quickly


implement robust admin interfaces without the
usual repetitive work.
3.1 Activating the Admin Interface

• Activating Django's admin interface involves three steps:

1. Add admin metadata to models: Mark models that should have an


admin interface by adding an inner Admin class.

2. Install the admin application: Add django.contrib.admin to


INSTALLED_APPS in your settings and run python manage.py syncdb
to set up the necessary database tables

3.Add the admin URL pattern: Ensure your urls.py includes the admin URL
pattern.

from django.conf.urls.defaults import *


urlpatterns = patterns('', (r'^admin/', include('django.contrib.admin.urls')), )
3.2 Using the Admin Interface
The Django admin interface is designed to be user-friendly, even for nontechnical users. Steps to how to use them:

Logging In
The admin interface starts with a login screen where you use your super user
credentials.
Main Index Page
• listing all objects with an Admin declaration.
• You can manage users, groups, and permissions from this page.
Change Lists and Edit Forms
Change Lists: These are index pages for objects, showing a list of entries. You can
customize which fields appear and add features like search fields and filters.

Edit Forms: Used to create and modify objects, these forms show fields defined in
your model with appropriate widgets for each field type
(e.g., date pickers for date fields).
Input Validation
The admin interface includes input validation,
highlighting errors if required fields are left blank or
invalid data is entered.
Object History
Each object has a History button to view a log of
changes made through the admin interface.
Deletion Confirmation
Deleting an object requires confirmation. The
interface shows all related objects that will also be
deleted to prevent accidental data loss.
Managing Users, Groups, and Permissions

• User Management: Users can be created, edited, and deleted


through the admin interface. User objects include fields for
username, password, email, and real name.
• User Permissions: Users have three flags:
– is active: Controls if the user can access any login-required URLs.
– is staff: Allows the user to log in to the admin interface.
– is superuser: Grants full access to all admin features, bypassing
regular permissions.
• Permissions: Each model has create, edit, and delete
permissions. These are used to control what actions users can
perform.
• Groups: Users can be assigned to groups, which are sets of
permissions applied to all members. Groups make it easy to
manage permissions for many users at once.
3.3 Customizing the Admin Interface
• Enhancing model admin declarations to improve
data management.

• Using Django's template system to change the


look and feel of the admin pages.

• Modifying the admin index page to prioritize


important applications and improve navigation.
3.4 Reasons to use Admin Interfaces
1. Data Entry:
Primary Use: The admin interface is ideal for any data entry tasks.
It allows content producers to input data while developers focus on building the public-
facing interface.

Example: At a newspaper, a reporter enters data about a special report through the
admin interface while developers work on the feature’s frontend.
2.Inspecting Data Models:
Initial Testing: When a new model is defined, developers use the admin interface to enter dummy data.
This helps quickly identify and correct data modeling mistakes by providing a graphical representation of the
model.

3. Managing Acquired Data:


• Data Corrections: For sites that acquire data automatically (e.g., through WEB scraping or
APIs), the admin interface is useful for manually editing and correcting any issues that arise with the
acquired data.

• Example: A site like chicagocrime.org, which collects data automatically, can use the admin interface to
correct errors in the acquired data.
BENEFITS OF ADMIN INTERFACES
• Ease of Use: It is designed for nontechnical users,
making it easy for content producers to manage data
without needing technical skills.

• Efficiency: By enabling simultaneous work of content


producers and developers, the admin interface
streamlines the development process.

Flexibility: The interface is not just for data entry but
also for inspecting and managing data, providing a
versatile tool for various backend tasks.
3.5 Form Processing
Display the Form:
The form is presented to the user, allowing them to input data. This can be an initial empty form or
a form pre-filled with existing data.
Receive the Input:
When the user submits the form, the input data is sent to the server, typically via a POST request,
though GET requests can also be used for forms like search.
Validate the Input:
The server checks the submitted data against the validation rules defined for the form fields. This
includes checking required fields, data types, value ranges, and any custom validation rules.
Handle Valid Data:
If the form data is valid, it is processed. This might involve saving the data to a database, sending an
email, or performing other actions depending on the form’s purpose.
Handle Invalid Data:
If the form data is invalid, the form is re-rendered with error messages and the user’s input,
allowing the user to correct their mistakes without having to re-enter all the data.
Render a Response:
After processing the form, the server sends a response back to the client. This could be a new page,
a confirmation message, or a re-rendered form with error messages.
3.6 Form Submissions
• When a user fills out a form and it passes validation, we often want to perform some action with the data.
• steps to send an email with the user's feedback using Django's email package is demonstrated
Steps:
1. Validate the Form Data
check if the form data is valid using the is_valid() method. If the form is valid, access the cleaned data.
form = ContactForm(request.POST)
if form.is_valid():
# Access the cleaned data
topic = form.cleaned_data['topic']

2.Send the Email


Use Django's send_mail function to send the feedback via email. This function requires the subject, message body,
sender's email, and a list of recipient emails.

from django.core.mail import send_mail send_mail( 'Feedback from your site, topic: %s' % topic, message,
sender, ['administrator@example.com'] )

3. Redirect to a Confirmation Page

After sending the email, redirect the user to a confirmation page to inform them that their feedback has been
submitted successfully.
Use of Post() Request()method in python

import requests

url='https://www.w3schools.com/python/demopage.php'
myobj = {'somekey': 'somevalue'}
x = requests.post(url, json = myobj)
print(x.text)

• The get() method sends a GET request to the specified url.

requests.get(url, timeout=2.50)
API in General
• APIs are mechanisms that enable two
software components to communicate with
each other using a set of definitions and
protocols.
• For example, the weather bureau's software
system contains daily weather data. The
weather app on your phone “talks” to this
system via APIs and shows you daily weather
updates on your phone.
Application Programming Interface
Including Other URLconfs
• include() function to manage URLs across different
applications or modules.
1. Purpose of include():

• Allows inclusion of other URLconfs into the current


URLconf, effectively "nesting" URLs.

• Simplifies URL management by breaking down large


URLconfs into smaller, reusable components
• Basic Usage:
• Syntax: include(module_or_pattern_list,
namespace=None, app_name=None)
• Example: include('myapp.urls')

• Behavior:
• When Django encounters include(), it removes the part of
the URL that matched up to that point and passes the
remaining string to the included URLconf for further
processing.

• Useful for structuring URLs hierarchically and separating


concerns between different parts of an application.
• Captured Parameters:
• Parameters captured in the parent URLconf are
passed down to the included URLconf.
Example: r'^(?P<username>\w+)/blog/'
include('foo.urls.blog')
• Ensures captured parameters are available to all
views within the included URLconf.
• Extra Options:
• Additional options (as a dictionary) can be passed
to include() to be applied to every line in the
included URLconf.
• Example: include('inner', {'blogid': 3})
Best Practices

• Organize URLconfs logically to maintain clarity


and separation of concerns.
• Use include() for modularization and
reusability, especially in large projects or across
multiple applications.
• Ensure consistency in parameter passing and
option usage across included URLconfs to avoid
unexpected behavior.
Conclusion
• Django developers can create scalable and
maintainable URL structures that enhance the
overall organization of their web applications.
DRY Principle in Django
• In Django, DRY stands for "Don't Repeat Yourself," which is a software development principle that promotes code
reuse and reduces duplication.

• The DRY principle emphasizes the importance of writing modular, reusable code and avoiding repetition wherever
possible.

• Django provides several mechanisms to help developers follow this principle:

• Django's URL dispatcher: It allows you to define URL patterns and map them to corresponding views.

• Template system: Django's template language supports template inheritance, allowing you to define base templates
that contain common elements shared across multiple pages.

• Model inheritance: Django's object-relational mapping (ORM) supports model inheritance, enabling you to define
common fields and behaviors in a base model and derive specialized models from it.

• Middleware: Django's middleware framework lets you define reusable components that process requests and
responses.

• Middleware can be used to handle common tasks such as authentication, session management, and caching,
eliminating the need to repeat the same logic in multiple views.
Module -4
Generic Views
• Use generic views:
• Less code is better These views represent a
common case of basic Web development:
• getting data from the database according to a
parameter passed in the URL.
• loading a template and returning the rendered
template.
• Generic views abstract common patterns to the
point where you don’t even need to write Python
code to write an app

You might also like