0% found this document useful (0 votes)
8 views19 pages

Module - 3 Pgms

The document outlines several Django programs, including customizations for admin pages using Writer and Publication models, creating feedback forms, sending emails through contact forms, and using model forms to save data in the database. Each section provides code snippets for models, views, forms, and templates, along with instructions for setting up and running the applications. Additionally, it includes guidance on configuring email settings for sending messages from the application.

Uploaded by

chan3024cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

Module - 3 Pgms

The document outlines several Django programs, including customizations for admin pages using Writer and Publication models, creating feedback forms, sending emails through contact forms, and using model forms to save data in the database. Each section provides code snippets for models, views, forms, and templates, along with instructions for setting up and running the applications. Additionally, it includes guidance on configuring email settings for sending messages from the application.

Uploaded by

chan3024cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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 settings.py and urls.py files in
your project

Models.py

from django.db import models

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

from django.contrib import admin


from adminpage_custom.models import Writer, Publication

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:

1) Python manage.py makemigrations


2) Python manage.py migrate

Run the server:

1) python manage.py runserver

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:

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 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

from django import forms


class FeedbackForm(forms.Form):
name = forms.CharField(max_length=100, label='Your Name')
email = forms.EmailField(label='Your Email')
subject = forms.CharField(max_length=200, label='Subject')
message = forms.CharField(widget=forms.Textarea, label='Your
Feedback')

urls.py

from django.urls import path


from . import views
urlpatterns = [
# ... other URL patterns
path('feedback/', views.feedback, name='feedback'),
]

Views.py

from django.shortcuts import render


from .forms import FeedbackForm

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!'}
)

return render(request, 'feedback.html', {'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 forms.py by taking an
example of contact form:

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!'}
)

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>
{{ 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:

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 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

from django.shortcuts import render


from .forms import Contactfm

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

from django.urls import path


from . import views
urlpatterns = [
# ... other URL patterns
path('modelforms/', views.contact_view, name='contact_view'),
]

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

from django import forms


from .models import Contact

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:

By using python manage.py shell:


See the data stored in the database:
Run the below lines in the interactive console:
from modelforms.models import Contact
Contact.objects.all().values()
Below result is obtained:
<QuerySet [{'id': 1, 'subject': 'good afternoon', 'email': '[email protected]',
'message': 'good afternoon\r\ngood afternoon\r\ngood afternoon\r\ngood
afternoon'}]>

You might also like