The Django Admin Site
Prof.Latha
1
6/27/2024
django.contrib Packages
Prof.Latha
2
6/27/2024
Activating the Admin Interface
Prof.Latha
3
6/27/2024
Activating the Admin Interface
Prof.Latha
4
6/27/2024
Activating the Admin Interface
Prof.Latha
5
6/27/2024
# Include these import statements
from django.contrib import admin admin.autodiscover()
# And include this URLpattern...
urlpatterns = patterns('',
# ...
(r'^admin/', include(admin.site.urls)), #
)
Using the Admin Site
Prof.Latha
6
6/27/2024
User edit form
SELECT * FROM auth_user
Prof.Latha
7
6/27/2024
The user edit form
Prof.Latha
8
6/27/2024
Adding Your Models to the Admin Site
Prof.Latha
9
6/27/2024
from django.contrib import admin
from mysite.student.models import Student
#or from .models import Book
admin.site.register(Book)
How the Admin Site Works
Prof.Latha
10
6/27/2024
Making Fields Optional
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField
By default, all fields have blank=False, which means blank values are not allowed.
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True)
Prof.Latha
11
6/27/2024
Making Date and Numeric Fields Optional
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField(blank=True, null=True)
Prof.Latha
12
6/27/2024
Customizing Field Labels
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
email = models.EmailField('e-mail', blank=True)
Prof.Latha
13
6/27/2024
Custom ModelAdmin Classes
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True,
verbose_name='e-mail')
def unicode (self):
return u'%s %s' % (self.first_name, self.last_name)
Prof.Latha
14
6/27/2024
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name')
admin.site.register(Author, AuthorAdmin)
Add a simple search bar
search_fields = ('first_name', 'last_name')
Prof.Latha
15
6/27/2024
Filter content based on date
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
admin.site.register(Publisher)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)
Prof.Latha
16
6/27/2024
Filter and order data based on publication date
list_filter = ('publication_date',)
# Ascending order
ordering = ('publication_date',)
Or
list_filter = ('publication_date',)
# Ascending order
ordering = ('publication_date',)
date_hierarchy = 'publication_date'
Prof.Latha
17
6/27/2024
Customizing Edit Forms
For example, in our book database, we could prevent the publication_date field from being editable:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
ordering = ('-publication_date',)
fields = ('title', 'authors', 'publisher',)
#make sure publication_date field should be set to null in model.py
publication_date = models.DateField(blank=True, null=True)
Prof.Latha
18
6/27/2024
Prof.Latha
19
6/27/2024
Forms-Getting Data from the Request Object
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world“)
HttpRequest objects contain several pieces of information about the currently requested URL,
Prof.Latha
20
6/27/2024
Always use the attributes/methods outlined in Table 7-1 instead of hard-coding URLs in your views. # BAD!
def current_url_view_bad(request):
return HttpResponse("Welcome to the page at /current/")
# GOOD
def current_url_view_good(request):
return HttpResponse("Welcome to the page at %s" % request.path)
Prof.Latha
21
6/27/2024
Other Information About the Request
"Mozilla 5.0 (X11; U; Linux i686) Gecko/20080829 Firefox/2.0.0.17"
Prof.Latha
22
6/27/2024
request.META
# BAD!
def ua_display_bad(request):
ua = request.META['HTTP_USER_AGENT']
# Might raise KeyError!
return HttpResponse("Your browser is %s" % ua)
Prof.Latha
23
6/27/2024
# GOOD (VERSION 1)
def ua_display_good1(request):
try:
ua = request.META['HTTP_USER_AGENT']
except KeyError:
ua = 'unknown'
return HttpResponse("Your browser is %s" % ua)
# GOOD (VERSION 2)
def ua_display_good2(request):
ua = request.META.get('HTTP_USER_AGENT', 'unknown')
return HttpResponse("Your browser is %s" % ua)
Information About Submitted Data
Prof.Latha
24
6/27/2024
A Simple Form-Handling Example
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
Prof.Latha
25
6/27/2024
The accompanying template, search_form.html, could look like this:
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
A Simple Form-Handling Example
The URLpattern in urls.py could look like this:
from mysite.books import views
urlpatterns = patterns('', (r'^search-form/$', views.search_form),
)
Run server & observe the output says 404 error when you give /search
Fix the error with following code
urlpatterns = patterns('', (r'^search-form/$', views.search_form),
(r'^search/$', views.search),
)
Prof.Latha
26
6/27/2024
# views.py
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
here’s what happens:
The HTML <form> defines a variable q. When it’s submitted, the value of q is sent via GET (method="get") to the URL /search/.
The Django view that handles the URL /search/ (search()) has access to the q value in request.GET.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from mysite.books.models import Book
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title icontains=q)
return render_to_response('search_results.html', {'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
Prof.Latha
27
6/27/2024
<p>You searched for: <strong>{{ query }} </strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}
Improving Our Simple Form-Handling Example
from django.http import HttpResponse
from django.shortcuts import render_to_response
from mysite.books.models import Book
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title icontains=q)
return render_to_response('search_results.html',
{'books': books, 'query': q})
else:
return render_to_response('search_form.html', {'error': True})
Prof.Latha
28
6/27/2024
Prof.Latha
29
6/27/2024
Prof.Latha
30
6/27/2024
Prof.Latha
31
6/27/2024
Prof.Latha
32
6/27/2024
Prof.Latha
33
6/27/2024
Prof.Latha
34
6/27/2024
Prof.Latha
35
6/27/2024
Prof.Latha
36
6/27/2024
Prof.Latha
37
6/27/2024
Thank You