Module - 3 Pgms
Module - 3 Pgms
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 settings.py and urls.py files in
your project
Models.py
class Writer(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField('e-mail', blank=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Publication(models.Model):
title = models.CharField(max_length=30)
publisher = models.CharField(max_length=40)
published_date = models.DateField()
writers = models.ManyToManyField(Writer)
def __str__(self):
return self.title
admin.py
class WriterAdmin(admin.ModelAdmin):
list_display = ('last_name', 'email', 'first_name')
search_fields = ('first_name', 'last_name')
list_filter = ('first_name', 'last_name')
class PublicationAdmin(admin.ModelAdmin):
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',)
admin.site.register(Writer, WriterAdmin)
admin.site.register(Publication, PublicationAdmin)
Running Migrations:
then follow the link to login to admin page using username and password:
http://127.0.0.1:8000/admin/
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:
Note: Register the app in your project folder using settings.py and urls.py 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>
Feedback.html
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h1>Feedback Form</h1>
<form method="post">
{% csrf_token %}
{{ 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 }}
</div>
<input type="submit" value="Submit Feedback">
</form>
</body>
</html>
forms.py
urls.py
Views.py
def feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
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!'}
)
Note: Register the app in your project folder using settings.py and urls.py files
in your project
Forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=200, label='Subject')
message = forms.CharField(widget=forms.Textarea, label='Your Feedback')
Views.py
from django.shortcuts import render
from django.core.mail import send_mail
from django import forms
from forms_app.forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
message = cd['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
send_mail(
cd['subject'],
cd['message'],
cd.get('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!'}
)
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>
{{ form.subject.errors }}
{{ form.subject.label_tag }}
{{ form.subject }}
</div>
<div>
{{ form.Contactinfo.errors }}
{{ form.Contactinfo.label_tag }}
{{ form.Contactinfo }}
</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 settings.py file of the project file mention the code anywhere you want:
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
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:
[email protected]). Here I am using gmail so email host will be
'smtp.gmail.com'. 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 settings.py 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:
Use this password without spaces in the settings.py file of your Django containing
email’s code (EMAIL_HOST_PASSWORD).
Output:
4) Program to use modelforms and save the details in the database:
Models.py
from django.db import models
class Contact(models.Model):
subject = models.CharField(max_length=100)
email = models.EmailField(blank=True)
message = models.TextField()
def __str__(self):
return self.subject
views.py
def contact_view(request):
if request.method == 'POST':
form = Contactfm(request.POST)
if form.is_valid():
form.save()
return render(request, 'success.html', {'message': 'Form submitted
successfully!'})
else:
form = Contactfm()
return render(request, 'form.html', {'form': form})
urls.py
form.html
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% 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 }}
<label for="id_email">Your email address:</label>
{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Message:</label>
{{ form.message }}
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
Success.html
<html>
<head>
<title>Form Submission Successful</title>
</head>
<body>
<h1>Success!</h1>
<p>{{ message }}</p>
</body></html>
Forms.py
class Contactfm(forms.ModelForm):
class Meta:
model = Contact
fields = ['subject', 'email', 'message']
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
Output: