Module – 3 Programs
1) Program for showing all the customizations to be done to admin page taking
writer and publication models as example:
Note: Register the app in your project folder using [Link] and [Link] files in
your project
[Link]
from [Link] import models
class Writer([Link]):
first_name = [Link](max_length=30)
last_name = [Link](max_length=40)
email = [Link]('e-mail', blank=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Publication([Link]):
title = [Link](max_length=30)
publisher = [Link](max_length=40)
published_date = [Link]()
writers = [Link](Writer)
def __str__(self):
return [Link]
[Link]
from [Link] import admin
from adminpage_custom.models import Writer, Publication
class WriterAdmin([Link]):
list_display = ('last_name', 'email', 'first_name')
search_fields = ('first_name', 'last_name')
list_filter = ('first_name', 'last_name')
class PublicationAdmin([Link]):
fields = ('title', 'publisher', 'published_date', 'writers')
list_display = ('title', 'publisher', 'published_date')
list_filter = ('published_date',)
date_hierarchy = 'published_date'
ordering = ('-published_date',)
#filter_horizontal = ('writers',)
#raw_id_fields = ('writers',)
autocomplete_fields = ('writers',)
[Link](Writer, WriterAdmin)
[Link](Publication, PublicationAdmin)
Running Migrations:
1) Python [Link] makemigrations
2) Python [Link] migrate
Run the server:
1) python [Link] runserver
then follow the link to login to admin page using username and password:
[Link]
To see all the customizations made to admin page, check the registered model in
the admin page.
Only few screen shots are given here. To get all the
Output:
All the below figures showing customizations done to the publications and
writers model:
Figure representing the writers and publications page
Figure representing the publication page
Figure representing customizations done to the writers page
Figure: Representing the manytomany field named as writers.
2) Program for creating simple feedback forms:
Note: Register the app in your project folder using [Link] and [Link] files
in your project.
In templates folder:
Feedback_success.html
<!DOCTYPE html>
<html>
<head>
<title>Feedback Submitted</title>
</head>
<body>
<h1>Thank you for your feedback!</h1>
<p>We appreciate your comments, {{ name }}, and will review them
shortly.</p>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h1>Feedback Form</h1>
<form method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<input type="submit" value="Submit Feedback">
</form>
</body>
</html>
[Link]
from django import forms
class FeedbackForm([Link]):
name = [Link](max_length=100, label='Your Name')
email = [Link](label='Your Email')
subject = [Link](max_length=200, label='Subject')
message = [Link](widget=[Link], label='Your
Feedback')
[Link]
from [Link] import path
from . import views
urlpatterns = [
# ... other URL patterns
path('feedback/', [Link], name='feedback'),
]
[Link]
from [Link] import render
from .forms import FeedbackForm
def feedback(request):
if [Link] == 'POST':
form = FeedbackForm([Link])
if form.is_valid():
# Process the feedback data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
return render(request, 'feedback_success.html', {'name': name})
else:
form = FeedbackForm(initial={'subject': 'I love your Site!'}
)
return render(request, '[Link]', {'form': form})
Output:
Feedback form for filling the details
After filling the feedback form, The above page is displayed.
3) Program to send mail to the particular email-id using [Link] by taking an
example of contact form:
Note: Register the app in your project folder using [Link] and [Link] files
in your project
[Link]
from django import forms
class ContactForm([Link]):
subject = [Link](max_length=200, label='Subject')
message = [Link](widget=[Link], label='Your Feedback')
[Link]
from [Link] import render
from [Link] import send_mail
from django import forms
from forms_app.forms import ContactForm
def contact(request):
if [Link] == 'POST':
form = ContactForm([Link])
if form.is_valid():
cd = form.cleaned_data
message = cd['message']
num_words = len([Link]())
if num_words < 4:
raise [Link]("Not enough words!")
send_mail(
cd['subject'],
cd['message'],
[Link]('e-mail', 'enter sender’s email here'),
['enter recipient’s name here'],
)
return render(request, 'contact_success.html')
else:
form = ContactForm(
initial={'subject': 'I love your Site!'}
)
return render(request, 'contact_form.html', {'form': form})
contact_form.html:
<!DOCTYPE html>
<html>
<head>
<title>Contact Us Form</title>
</head>
<body>
<h1>Contact Form</h1>
<form method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<div>
{{ [Link] }}
{{ [Link].label_tag }}
{{ [Link] }}
</div>
<input type="submit" value="Submit Info">
</form>
</body>
</html>
Contact_success.html
<!DOCTYPE html>
<html>
<head>
<title>Information Taken </title>
</head>
<body>
<h1>Thank you for your details!</h1>
<p>Thankyou for giving the contact info, and will contact you shortly.</p>
</body>
</html>
In [Link] file of the project file mention the code anywhere you want:
DEBUG = True
EMAIL_BACKEND = '[Link]'
EMAIL_HOST = '[Link]'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ' sender’s email '
EMAIL_HOST_PASSWORD = ' '
Note :
• For EMAIL_HOST_USER give the senders email address. (for example:
xxx@[Link]). Here I am using gmail so email host will be
'[Link]'. You can use different email host for different email-ids
• For EMAIL_HOST_PASSWORD give the password by following the below
steps:
i) Go to the gmail → manage my account → search for app passwords in
the search bar → then give the name for the app and 12-character
password will be created automatically.
ii) After getting the password, use that password in
EMAIL_HOST_PASSWORD in [Link] file.
iii) This will be connecting the Django app to the gmail to send the form’s
data to the gmail. From this we can send the forms data to particular
recipient’s email-id
Gmail – Settings:
Figure showing the searching of app passwords
Give the name of the app here. After giving the name. There will be a 12 – character
password created.
Use this password without spaces in the [Link] file of your Django containing
email’s code (EMAIL_HOST_PASSWORD).
Output:
4) Program to use modelforms and save the details in the database:
[Link]
from [Link] import models
class Contact([Link]):
subject = [Link](max_length=100)
email = [Link](blank=True)
message = [Link]()
def __str__(self):
return [Link]
[Link]
from [Link] import render
from .forms import Contactfm
def contact_view(request):
if [Link] == 'POST':
form = Contactfm([Link])
if form.is_valid():
[Link]()
return render(request, '[Link]', {'message': 'Form submitted
successfully!'})
else:
form = Contactfm()
return render(request, '[Link]', {'form': form})
[Link]
from [Link] import path
from . import views
urlpatterns = [
# ... other URL patterns
path('modelforms/', views.contact_view, name='contact_view'),
]
[Link]
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
{% if [Link] %}
<p style="color: red;">
Please correct the error{{ [Link]|pluralize }} below.
</p>
{% endif %}
<form method="post">
{% csrf_token %}
<div class="field">
{{ [Link] }}
<label for="id_subject">Subject:</label>
{{ [Link] }}
</div>
<div class="field">
{{ [Link] }}
<label for="id_email">Your email address:</label>
{{ [Link] }}
</div>
<div class="field">
{{ [Link] }}
<label for="id_message">Message:</label>
{{ [Link] }}
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
<html>
<head>
<title>Form Submission Successful</title>
</head>
<body>
<h1>Success!</h1>
<p>{{ message }}</p>
</body></html>
[Link]
from django import forms
from .models import Contact
class Contactfm([Link]):
class Meta:
model = Contact
fields = ['subject', 'email', 'message']
def clean_message(self):
message = self.cleaned_data['message']
num_words = len([Link]())
if num_words < 4:
raise [Link]("Not enough words!")
return message
Output:
By using python [Link] shell:
See the data stored in the database:
Run the below lines in the interactive console:
from [Link] import Contact
[Link]().values()
Below result is obtained:
<QuerySet [{'id': 1, 'subject': 'good afternoon', 'email': 'sandhyan@[Link]',
'message': 'good afternoon\r\ngood afternoon\r\ngood afternoon\r\ngood
afternoon'}]>