Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Full Stack Development Module 3

MODULE 3
Django Admin is a really great tool in Django, it is actually a CRUD- user interface of all your
models.

CRUD stands for Create Read Update Delete

1. Activating the Admin Interface:

There are three steps you’ll need to follow to activate it:

1. Add admin metadata to your models. Not all models can be editable by admin users, so you
need to “mark” models that should have an admin interface. You do that by adding an inner
Admin class to your model. The Admin declaration flags the class as having an admin interface.

Example: To add an admin interface to our Book model

2. Install the admin application. Do this by adding django.contrib.admin to your


INSTALLED_APPS setting and running python manage.py syncdb. This second step will install
the extra database tables the admin interface uses.

3. Add the URL pattern to your urls.py. . If you’re still using the one created by startproject, the
admin URL pattern should be already there,your URL patterns should look like the following:

DSATM Page 1
Full Stack Development Module 3
Now run python manage.py runserver to start the development server. You’ll see something like
this:

2. Using the Admin Interface:

1. Logging In: You will use the username and password created during the initial setup of your
superuser account. The admin interface is designed to be used by nontechnical users, and as such
it should be pretty self-explanatory.

Each object given an Admin declaration shows up on the main index page, as shown in Figure

2. Navigating the Interface:

• Upon successful login, you can manage various aspects of your application, including:

o Users: Create, edit, and manage user accounts within the system.
o Groups: Organize users into groups for permission control (explained later).
o Permissions: Define access levels for specific users or groups.

• The main page displays a list of all registered models in your application (each model
represents a data structure).

Managing Data:

• Change Lists:

DSATM Page 2
Full Stack Development Module 3
 These are essentially tables listing all instances (objects) of a particular model.
 You can customize the displayed fields and utilize features like:
 Date filtering: Refine the list based on specific date ranges.
 Search functionality: Search for objects by specific criteria.
 Filtering options: Narrow down the list based on pre-defined filters.

• Edit Forms:

 Edit existing objects or create new ones.


 Each defined field in your model appears here with appropriate input widgets (e.g.,
calendars for date/time, dropdown menus for foreign keys).
 The interface validates your input, preventing errors like saving blank required fields.

3. Users, Groups, and Permissions:

The Django admin interface offers a permission system to control user access.

As a superuser, you have full access, but you can define limited access for other users.

Managing Users and Groups:

• Edit users and permissions through the admin interface like any other object.
• Access the User and Group models from the admin index.

User Object Details:

• Standard fields: Username, password, email, and real name.


• Permission-related fields:
o is_active: Controls user access (active/inactive).
o is_staff: Determines admin interface access (staff/non-staff).
o is_superuser: Grants full, unrestricted access.

Assigning User Permissions:

• Regular admin users (active, non-superuser staff) have access based on assigned
permissions.
• Each editable object has three permissions: create, edit, and delete.
• Assigning permissions grants users specific actions on objects.

Utilizing Groups:

• Groups represent sets of permissions applied to all members.


• Useful for assigning identical permissions to many users efficiently.

4. Customizing the Admin Interface:

DSATM Page 3
Full Stack Development Module 3
The Django admin interface offers customization options to improve usability for managing your
data. Here's an overview focusing on our Book model Challenge:

Efficient Book Management:

• Currently, the Book model's change list displays only the model's string representation.

• This becomes cumbersome when dealing with large datasets (hundreds or thousands of books).

Solution: Improved Display, Search, and Filtering:

Each of those lines instructed the admin interface to construct a different piece of this interface:

• The list_display option controls which columns appear in the change list table. By default, the
change list displays only a single column that contains the object’s string representation. Here,
we’ve changed that to show the title, publisher, and publication date.

• The list_filter option creates the filtering bar on the right side of the list. We’ve allowed
filtering by date and by publisher.

• The ordering option controls the order in which the objects are presented in the admin
interface. It’s simply a list of fields by which to order the results; prefixing a field with a minus
sign reverses the given order. In this example, we’re ordering by publication date, with the most
recent first.

• The search_fields option creates a field that allows text searches. It allows searches by the title
field.

DSATM Page 4
Full Stack Development Module 3
Now we focuses on customizing the Django admin interface to enhance its functionality and user
experience.

1. Customizing the Admin Interface's Look and Feel: The admin interface can be tailored to
your preferences. You can modify:

• Visual appearance: Change colors, fonts, and layouts to suit your needs.
• Displayed information: Control which fields and data are visible in change lists and edit
forms. • Functionality: Implement custom actions, filters, and validations for specific use
cases.

2. Customizing the Admin Index Page: The admin index page provides an overview of all
registered models in your application. You can customize it to:

• Reorder or hide models: Prioritize frequently used models or hide irrelevant ones.
• Add custom navigation links: Integrate shortcuts to frequently accessed functionalities.
• Display additional information: Include summaries or statistics relevant to your
application.

3. When and Why to Use the Admin Interface: The Django admin interface offers several
advantages:

• Rapid Prototyping: Quickly set up a functional interface for managing data during
development.
• Content Management: Provide a user-friendly interface for non-technical users to add,
edit, and delete data.
• User Management: Create and manage user accounts with defined permissions for
secure data access control

Form Processing:
Django provides a robust framework for handling user input through forms. This document
offers an introduction to form processing concepts in Django.

1. Forms and User Interaction:


 Forms are essential components for collecting user input in web applications.
 Django offers a streamlined approach to creating and processing forms.

Key Components:

 Form Class: Defines the structure of your form, including fields, validation rules, and
widgets (visual representations of fields like text inputs or dropdowns).
 Form Instance: An object representing a specific form at a particular point in time.
DSATM Page 5
Full Stack Development Module 3

 Form Processing: The process of validating, cleaning, and handling user-submitted data
from a form.

2. Benefits of Django Forms:


1. Simplified Form Creation: Django provides built-in form fields and widgets, reducing
boilerplate code.
2. Built-in Validation: Define validation rules to ensure data integrity and prevent invalid
submissions.
3. Automatic CSRF Protection: Django safeguards against Cross-Site Request Forgery
attacks by including CSRF tokens in forms.
4. Seamless Integration: Django forms integrate seamlessly with Django views and
templates for efficient data handling
5.

3. Search:
Implementing Search Functionality in Django. This document outlines the steps involved in
adding a search function to a Django application focused on books.

Example:We will write this search view into our view module (mysite.books.views):

HTML Template Function:

DSATM Page 6
Full Stack Development Module 3

Understanding User Input:(Explanation about above program)

• Accessing user input submitted through forms:

 request.GET: Used to retrieve data submitted via the GET method (typically form data).
 request.POST: Used to retrieve data submitted via the POST method (often for more
complex forms).

1. URL Configuration: Add a new URL pattern to your urls.py file (r'^search/$',
'mysite.books.views.search' pointing to a search view).

2. Search View Logic:

o Retrieve the search query from the GET data using request.GET.get('q', '').
o get(key, default): Retrieves the value for the specified key ('q') from the dictionary
(request.GET).
o Provides a default value (' ') if the key is not present.
 Utilize Q objects to construct complex database queries:
Allow searching by book title or author name (case-insensitive).
icontains performs case-insensitive search using the database's LIKE operator.
 Filter the book queryset based on the search criteria.

DSATM Page 7
Full Stack Development Module 3
 Consider using .distinct() to eliminate duplicate results (e.g., books with multiple
matching authors).

3. Form and User Experience:

 Set the form's action attribute to .: Submits the form to the current URL, allowing for a
single view handling both form display and search results.
 Re-render the search query in the search results page for easy refinement.
 Apply the escape filter to any user-submitted query before displaying it on the page to
prevent XSS attacks.

Key Points:

• Django's database layer safeguards against malicious content within database lookups.

• Always escape user-submitted data before displaying it to prevent security vulnerabilities like
XSS.

4. Creating a Feedback Form:


To build a simple feedback form and use it to illustrate Django’s forms framework in action.

This document outlines the process of creating a feedback form in Django, highlighting key
concepts for graduate students.

Importance of Feedback:

 User feedback is crucial for website development and improvement.


 Actively encourage user feedback, especially for growing applications.

Django Forms Framework: Django's forms framework simplifies creating and managing user
input forms.

1. Form Definition (forms.py):

• Forms are defined as Python classes, similar to models.

• Inherit from django.forms.Form.

• Each field in the form is represented by a field class from django.newforms (refer to Django
documentation for available field types).

• This form includes three fields: Our ContactForm consists of three fields

 topic: Choice field with options for bug reporting, suggestions, or other feedback.
 message: Text field for user feedback.

DSATM Page 8
Full Stack Development Module 3
 sender: Optional email field for user contact information.

Now let us look into Views.py

Now contact.html

DSATM Page 9
Full Stack Development Module 3
2. Form Functionality: Form objects offer various functionalities:

 Data validation: Ensures data meets defined criteria.


 Widget generation: Creates HTML input elements for each field.
 Error message construction: Provides informative messages for invalid data.
 Form rendering: Generates the complete HTML form structure (optional).

You need to define those yourself in the template, which gives you control over how the form
behaves when it is submitted. Label elements are included, making forms accessible out of the
box.

The forms framework separates out the presentation logic for each field into a set of widgets.
Each field type has a default widget, but you can easily override the default, or provide a custom
widget of your own

5. Processing the Submission:


This document explores advanced functionalities of Django forms, building upon your
understanding of basic form creation

. 1. Processing the Submission in Django Forms:

• Handling POST Requests:

 Your view function checks for POST requests to identify form submissions.
 Create a form instance using the submitted data (form = YourForm(request.POST))

• Form Validation:

 Use form.is_valid() to verify if all data meets validation rules.


 Upon successful validation, process the cleaned data (form.cleaned_data).
 Access individual cleaned field values using dictionary-like access (e.g.,
form.cleaned_data['message'])

DSATM Page 10
Full Stack Development Module 3
Example: use form.clean_data:

• Error Handling:

 If validation fails, the form object contains error messages for each invalid field.
 Access them using form.errors (dictionary containing field names and error messages).
 Render the form with errors in the template to inform the user for correction.

Example: To clean the data

Finally, we need to record the user’s feedback. The easiest way to do this is to email it to a site
administrator. We can do that using the send_mail function:

The send_mail function has four required arguments: the email subject, the email body, the
“from” address, and a list of recipient addresses. send_mail is a convenient wrapper around
Django’s EmailMessage class, which provides advanced features such as attachments, multipart
emails, and full control over email header

6. Custom Validation Rules:


• Django's built-in validation rules cover basic scenarios.

• Define custom validation methods within your form class for specific needs.

 Create methods starting with clean_ (e.g., clean_message).


 Perform custom validation logic within these methods.
 Raise a ValidationError with an appropriate error message if validation fails

DSATM Page 11
Full Stack Development Module 3
Example: Emails

Some of the emails contain just one or two words, hardly enough for a detailed missive. We
decide to adopt a new validation policy.

There are a number of ways to hook custom validation into a Django form. If our rule is
something we will reuse again and again, we can create a custom field type.

Additional validation on the message field, so we need to add a clean_message method to our
form:

7. A Custom Look and Feel:


• Django forms use default widgets for rendering input elements.

• Override default widgets to customize the form's appearance.

 Define custom widget classes inheriting from appropriate base widget classes (e.g.,
TextInput, Select).
 Override the render method in your widget class to generate the desired HTML markup.

Example: The list of errors in particular could do with some visual enhancement, and the

has a class attribute of errorlist for that exact purpose. The following CSS really makes our errors
stand out:

DSATM Page 12
Full Stack Development Module 3
Each field widget (<input type="text">,<select>,<textarea>or similar) can be rendered
individually by accessing {{ form.fieldname }}. Any errors associated with a field are available
as {{ form.fieldname.errors }}. We can use these form variables to construct a custom template
for our contact form.

{{ form.message.errors }} will display as a if errors are present and a blank string if the field is
valid

8. Creating Forms from Models:

• Django offers a shortcut for creating forms based on existing models using ModelForm.
 Inherit from django.forms.ModelForm instead of django.forms.Form.
 Specify the model class as an argument to the ModelForm constructor.
 Django automatically generates form fields based on the model's fields.
• ModelForm provides additional features:
 Pre-populating forms with existing model data for editing.
 Saving form data back to the model instance after successful validation.
Example: Our Publisher model class says that a publisher has a name, address, city,
state_province, country, and website. Duplicating this information in a form definition would
break the DRY(Don’t Repeat Yourself) rule. Instead, we can use a useful shortcut:
form_for_model():

DSATM Page 13
Full Stack Development Module 3

Advanced Views and URLconfs


Let’s explore concepts beyond basic Django views and URL configurations.
1. Streamlining Function Imports: There are two approaches
1. String Approach:
Advantages of the string approach are as follows:
• It’s more compact, because it doesn’t require you to import the view functions.
• It results in more readable and manageable URLconfs if your view functions are spread across
several different Python modules.
Example:

2. Object Approach:
Advantages of the function object approach are as follows:
• It allows for easy “wrapping” of view functions.
• It’s more “Pythonic”—that is, it’s more in line with Python traditions, such as passing functions
as objects. Both approaches are valid, and you can even mix them within the same URLconf.
Django offers another way of specifying the view function for a particular pattern in the
URLconf, you can pass a string containing the module name and function name rather than the
function object itself.

DSATM Page 14
Full Stack Development Module 3

A further shortcut you can take when using the string technique is to factor out a common “view
prefix.” In our URLconf example, each of the view strings starts with 'mysite.views', which is
redundant to type. We can factor out that common prefix and pass it as the first argu ment to
patterns(), like this:

2. Using Multiple View Prefixes


• Mixins are reusable code snippets providing specific functionalities.
• They are often used with class-based views for modularity.
Examples:
 LoginRequiredMixin: Ensures user is logged in for accessing a view.
 PermissionRequiredMixin: Requires specific user permissions for access.
 FormMixin: Simplifies form handling logic within class-based views.

3. Advanced URL Patterns:


• Django URL patterns offer more than just simple string matches.
• Regular expressions: Enable flexible matching of URL patterns.
• Capturing groups:
4. Using Named Groups:

DSATM Page 15
Full Stack Development Module 3
Django passes that captured text to the view function as a positional argument. In more
advanced usage, it’s possible to use named regular expression groups to capture URL bits
and pass them as keyword arguments to a view.
In Python regular expressions, the syntax for named regular expression groups is
(?P<name>pattern), where name is the name of the group and pattern is some pattern to
match.
Example: URLconf that uses non-named groups:

Example: Here’s the same URLconf rewritten to use named groups

5. Understanding the Matching/Grouping Algorithm:


Specifically, here’s the algorithm the URLconf parser follows with respect to named groups vs.
non-named groups in a regular expression.
• If there are any named arguments, it will use those, ignoring non-named arguments.
• Otherwise, it will pass all non-named arguments as positional arguments.
• In both cases, it will pass any extra options as keyword arguments.
6. Passing Extra Options to View Functions:

DSATM Page 16
Full Stack Development Module 3
Writing view functions those are quite similar, with only a few small differences.
Example: Two views whose contents are identical except for the template they use.

We’re repeating ourselves in this code, and that’s inelegant. At first, you may think to remove
the redundancy by using the same view for both URLs, putting parentheses around the URL to
capture it, and checking the URL within the view to determine the template, like so:

DSATM Page 17
Full Stack Development Module 3

DSATM Page 18

You might also like