Module 03
Module 03
Module 03
Module-03
Update settings.py:
Add to INSTALLED_APPS:
• 'django.contrib.admin'
• Ensure 'django.contrib.auth', 'django.contrib.contenttypes', and 'django.contrib.sessions'
are included. Uncomment if previously commented.
Update MIDDLEWARE_CLASSES:
• 'django.middleware.common.CommonMiddleware'
• 'django.contrib.sessions.middleware.SessionMiddleware'
• 'django.contrib.auth.middleware.AuthenticationMiddleware'
• Execute python manage.py syncdb to install the necessary database tables for the admin
interface.
• If not prompted to create a superuser, run python manage.py createsuperuser to create an
admin account.
Update urls.py:
Logging In:
• Visit the admin site and log in with the superuser credentials you created.
• If you can't log in, ensure you’ve created a superuser by running python manage.py
createsuperuser.
• After logging in, you'll see the admin home page listing all data types available for
editing. Initially, it includes only Groups and Users.
Data Management:
• Each data type in the admin site has a change list and an edit form.
• Change List: Displays all records of a data type, similar to a SELECT * FROM <table>
SQL query.
• Edit Form: Allows you to add, change, or delete individual records.
• Click the Change link in the Users row to load the change-list page for users.
• This page shows all users in the database, with options for filtering, sorting, and
searching.
• Filtering: Options are on the right.
• Sorting: Click a column header.
• Search: Use the search box at the top.
• Click a username to see the edit form for that user.
• Change user attributes such as first/last names and permissions.
• To change a user's password, click the Change Password Form link.
• Different field types have different input widgets (e.g., calendar controls for date fields,
checkboxes for Boolean fields).
• Add Record: Click Add in the appropriate column on the admin home page to access an
empty edit form for creating a new record.
• Delete Record: Click the Delete button at the bottom left of an edit form. Confirm the
deletion on the subsequent page, which may list dependent objects to be deleted as well.
• The admin interface validates input automatically. Errors will be displayed if you leave
required fields blank or enter invalid data.
History:
• When editing an object, a History link appears in the upper-right corner. This logs every
change made through the admin interface and allows you to review the change history.
• In the Django admin site, each field’s label is derived from its model field name.
• To customize a label, use the verbose_name attribute in your model field definitions.
Example:
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')
• Alternatively, you can pass verbose_name as a positional argument:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
• ModelAdmin classes allow customization of how models are displayed and managed in
the admin interface.
• Customizing Change Lists
• By default, change lists show the result of the model's __str__ or __unicode__ method.
You can specify which fields to display using the list_display attribute.
class AuthorAdmin(admin.ModelAdmin):
admin.site.register(Author, AuthorAdmin)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
search_fields = ('first_name', 'last_name')
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
ordering = ('-publication_date',)
class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher', 'publication_date')
• Excluding Fields
• Exclude fields by omitting them from the fields list:
class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher')
class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)
class BookAdmin(admin.ModelAdmin):
filter_vertical = ('authors',)
class BookAdmin(admin.ModelAdmin):
raw_id_fields = ('publisher',)
• Example Workflow:
1. A reporter meets with a developer to describe the data.
2. The developer creates Django models based on this data and sets up the
admin interface.
3. The reporter reviews the admin site and suggests any changes to the fields.
4. The developer updates the models accordingly.
5. The reporter begins entering data, allowing the developer to focus on
building views and templates.
1. Public Interfaces:
• Security and Usability: The admin interface is not designed for public use. It lacks
the security measures and user-friendly design necessary for a public-facing
application.
1. Introduction to Forms
• Django provides a built-in form handling functionality that simplifies the process
of handling HTML forms in web applications.
• Forms in Django are represented by Python classes that map to HTML form fields.
2. Creating a Form
• In Django, forms are created by subclassing the forms.Form class or the
forms.ModelForm class (for model-based forms).
• Each form field is represented by a class attribute, and the type of the field is
determined by the corresponding Django Field class.
Example:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
3. Rendering a Form
• Forms can be rendered in templates using the {{ form.as_p }} (for paragraph-based
rendering) or {{ form.as_table }} (for table-based rendering) template tags.
• Individual form fields can be rendered using {{ form.field_name }}.
7. Form Widgets
• Django provides a wide range of built-in form widgets (e.g., TextInput, Textarea,
CheckboxInput, Select, etc.) for rendering form fields.
• You can customize the rendering of form fields by specifying the widget argument
when defining the field.
9. CSRF Protection
• Django provides built-in protection against Cross-Site Request Forgery (CSRF)
attacks by including a CSRF token in forms.
• You need to include the {% csrf_token %} template tag in your form template to
generate the CSRF token.
Create a new file forms.py in your Django app directory, and add the following code
class FeedbackForm(forms.Form):
Create a new file feedback.html in your Django app's templates directory, and add the following
code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h1>Feedback Form</h1>
<form method="post">
{{ form.non_field_errors }}
<div>
{{ form.name.errors }}
{{ form.name.label_tag }}
{{ form.name }}
</div>
<div>
{{ form.email.errors }}
{{ form.email.label_tag }}
{{ form.email }}
</div>
<div>
{{ form.subject.errors }}
{{ form.subject.label_tag }}
{{ form.subject }}
</div>
<div>
{{ form.message.errors }}
{{ form.message.label_tag }}
{{ form.message }}
</form>
</body>
</html>
Create a new file feedback_success.html in your Django app's templates directory, and add the
following code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Submitted</title>
</head>
<body>
</body>
</html>
Open your Django app's views.py file and add the following code:
def feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
else:
form = FeedbackForm()
Open your Django app's urls.py file and add the following URL pattern:
urlpatterns = [
Start the Django development server and navigate to http://localhost:8000/feedback/ in your web
browser. You should see the feedback form.
Form submissions
1. Create a Form Class: Define a form class that inherits from forms.Form or
forms.ModelForm. This class defines the fields and validations for your form.
2. Render the Form in a Template: In your template, render the form using the {{ form }}
template tag or individual field tags like {{ form.field_name }}.
3. Check Request Method: In your view function, check if the request method is POST
(form submission) or GET (initial form load).
4. Create Form Instance with Data: If the request method is POST, create a form instance
with the submitted data using form = YourForm(request.POST) or form =
YourModelForm(request.POST).
5. Validate the Form: Call form.is_valid() to validate the form data against the defined fields
and validations.
6. Process Valid Form Data: If the form is valid (form.is_valid() returns True), access the
cleaned data using form.cleaned_data and perform any necessary operations (e.g., save to
the database, send an email, etc.).
8. Redirect or Render Success Page: After successful form processing, it's recommended
to redirect the user to a success page or a different view to prevent duplicate form
submissions on page refresh.
# forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
# views.py
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
return redirect('success_url')
else:
form = ContactForm()
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
• This method:
• Extracts the message from self.cleaned_data.
• Counts the words using split() and len().
• Raises a ValidationError if there are fewer than four words.
• Returns the cleaned message value.
• You can customize the form's appearance using CSS and custom HTML templates
for better control over the presentation.
<html>
<head>
<title>Contact us</title>
</head>
<h1>Contact us</h1>
{% if form.errors %}
</p>
{% endif %}
<div class="field">
{{ form.subject.errors }}
<label for="id_subject">Subject:</label>
{{ form.subject }}
</div>
<div class="field">
{{ form.email.errors }}
{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Message:</label>
</div>
</form>
</body>
</html>
This template:
Example
class Contact(models.Model):
subject = models.CharField(max_length=100)
email = models.EmailField(blank=True)
message = models.TextField()
def __str__(self):
return self.subject
Example
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
Example:
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
return message
Example
def contact_view(request):
form = ContactForm(request.POST)
if form.is_valid():
form.save()
else:
form = ContactForm()
Example
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
{% if form.errors %}
{% endif %}
<form method="post">
{% csrf_token %}
<div class="field">
{{ form.subject.errors }}
<label for="id_subject">Subject:</label>
{{ form.subject }}
</div>
<div class="field">
{{ form.email.errors }}
{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Message:</label>
{{ form.message }}
</div>
</form>
</html>
1. Define the Model: Establish your data structure with a Django model.
2. Create the Model Form: Generate a form using forms.ModelForm based on the model.
3. Add Custom Validation: Optionally include custom validation methods within the form.
4. Use the Form in Views: Implement form handling logic in Django views to process
submissions.
5. Create the Template: Design an HTML template to display and manage the form
interface.
URLConf Ticks
Example:
Example
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
(r'^hello/$', views.hello),
(r'^time/$', views.current_datetime),
(r'^time/plus/(d{1,2})/$', views.hours_ahead),
)
Example
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^hello/$', 'mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(d{1,2})/$', 'mysite.views.hours_ahead'),
)
• Advantage: No need to import view functions; Django handles imports
automatically.
Example:
urlpatterns = patterns('mysite.views',
(r'^hello/$', 'hello'),
(r'^time/$', 'current_datetime'),
(r'^time/plus/(d{1,2})/$', 'hours_ahead'),
• Flexibility:
• Both approaches are valid and can be mixed within the same URLconf depending
on personal coding style and project needs.
Basic Usage
Important Considerations
• Main URLconf:
urlpatterns = patterns('',
(r'^weblog/', include('mysite.blog.urls')),
(r'^photos/', include('mysite.photos.urls')),
(r'^about/$', 'mysite.views.about'),
1. Request: /weblog/2007/
• First URLconf: r'^weblog/' matches.
• Action: Strips weblog/.
• Remaining URL: 2007/.
• Result: Matches r'^(\d\d\d\d)/$' in mysite.blog.urls.
3. Request: /about/
• First URLconf: Matches r'^about/$'.
• Result: Maps to mysite.views.about view.
Mixing Patterns
• Flexibility: You can mix include() patterns with non-include() patterns within the same
URLconf.