Solution 2
Solution 2
If you want to present a list of books by a particular publisher, you can use the same
technique:
apress_books = {"queryset": Book.objects.filter(publisher__name="Apress Publishing"),
"template_name" : "books/apress_list.html"}
urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info),
(r'^books/apress/$', list_detail.object_list, apress_books),)
/*
$(".autocomplete").autocomplete({select: update_autocomplete});
$(".autocomplete").bind({"autocompleteselect": update_autocomplete});
$(".autocomplete").bind({"autocompletechange": update_autocomplete});
*/
});
C31 3
De
Li
0.4 a)Define Generic Views and its types
ta
Cr stUp
ilDe
ea Vida
Vile
te ewte
ewte
Vi Vi Vi
ew ew ew
Generic views in Django are reusable, abstract classes provided by the Django
framework that encapsulate common patterns used in web development.
Using generic views in Django is a powerful way to simplify the creation of
common views for tasks such as displaying database objects, handling form
submissions, and performing CRUD operations. Generic views provide pre-
built functionality for common patterns, reducing the amount of code you
need to write. Here's how to use generic views in Django.
Class-based generic list view (ListView) — a class that inherits from an
existing view. Because the generic view already implements most of the
functionality we need and follows Django best-practice, we will be able to
create a more robust list view with less code, less repetition, and ultimately
less maintenance.
Detail View: Detail View refers to a view (logic) to display one instances of
a table in the database. Detail View refers to a view (logic) to display a
particular instance of a table from the database with all the necessary details.
It is used to display multiple types of data on a single page or view, for
example, profile of a user.
descriptions:
Text/html: Represents HTML files, which are used to create web pages.
Text/css: Represents Cascading Style Sheets (CSS) files, which are used to
style HTML documents.
Application/javascript: Represents JavaScript files, which are used to add
interactivity and dynamic behavior to web pages.
Image/jpeg: Represents JPEG image files, which are commonly used for
photographs and other images with complex colors and details.
Image/png: Represents PNG image files, which are commonly used for
images with transparent backgrounds or simple graphics.
Application/pdf: Represents PDF (Portable Document Format) files, which
are used for documents that need to be displayed and printed consistently
across different platforms.
Application/json: Represents JSON (JavaScript Object Notation) files, which
are used for exchanging data between a server and a web application.
Application/xml: Represents XML (eXtensible Markup Language) files,
which are used for storing and transporting structured data.
Text/plain: Represents plain text files, which contain unformatted text
without any special styling or formatting.
Audio/mpeg: Represents MP3 audio files, which are commonly used for
storing and playing music and other audio recording
OR
a) Discuss how to create templates for each view with an example.
1. ListView
View:# views.py
class MyModelListView(ListView):
model = MyModel
template_name = 'myapp/mymodel_list.html'
context_object_name = 'objects'
Template:html
<!DOCTYPE html>
<html>
<head>
<title>MyModel List</title>
</head>
<body>
<h1>MyModel List</h1>
<ul>
{% endfor %}
</ul>
</body>
</html>
2. DetailView
View:
# views.py
class MyModelDetailView(DetailView):
model = MyModel
template_name = 'myapp/mymodel_detail.html'
context_object_name = 'object'
Template:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
3. CreateView
View:
# views.py
class MyModelCreateView(CreateView):
model = MyModel
template_name = 'myapp/mymodel_form.html'
Template:
<!DOCTYPE html>
<html>
<head>
<title>Create MyModel</title>
</head>
<body>
<h1>Create MyModel</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
</body>
</html>
4. UpdateView
View:
# views.py
class MyModelUpdateView(UpdateView):
model = MyModel
template_name = 'myapp/mymodel_form.html'
success_url = reverse_lazy('mymodel-list')
Template:
<!DOCTYPE html>
<html>
<head>
<title>Update MyModel</title>
</head>
<body>
<h1>Update MyModel</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
</body>
</html>
5. DeleteView
View:
# views.py
model = MyModel
template_name = 'myapp/mymodel_confirm_delete.html'
success_url = reverse_lazy('mymodel-list')
Template:
<!DOCTYPE html>
<html>
<head>
<title>Delete MyModel</title>
</head>
<body>
<form method="post">
{% csrf_token %}
</form>
</body></html>
def __str__(self):
return self.name
def export_mymodel_csv(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition']='attachment;
filename="mymodel.csv"'
writer = csv.writer(response)
# Write the header row
writer.writerow(['ID', 'Name', 'Description',
'Created At'])
return response
3. Configure the URL
Map the view to a URL in your urls.py file.
# urls.py
from django.urls import path
from .views import export_mymodel_csv
urlpatterns = [
path('export/csv/',export_mymodel_csv,
name='export_mymodel_csv'),]
4. Create a Template Link (Optional)
Optionally, create a link in one of your templates to trigger the CSV
download.
<!DOCTYPE html>
<html>
<head>
<title>Export CSV</title>
</head>
<body>
</body>
</html>
C31 4 Develop a registration page for student enrolment without page refresh using AJAX.
0.5 To create a registration page for student enrollment without page refresh
using AJAX (Asynchronous JavaScript and XML), you can follow these
steps:
Step 1: Set up the Django app and models: First, create a Django app for
student enrollment:
python manage.py startapp enrollment_app
Define the models for Course and Student in
enrollment_app/models.py:
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
course = models.ForeignKey(Course,
on_delete=models.CASCADE)
def __str__(self):
return self.name
Step 2: Create views and templates for registration: Define views and
templates for the registration form and submission handling. In
enrollment_app/views.py, add the following code:
from django.shortcuts import render
from django.http import JsonResponse
from .models import Course, Student
def registration_page(request):
courses = Course.objects.all()
return render(request, 'enrollment_app/registration.html',
{'courses': courses})
def register_student(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
course_id = request.POST.get('course')
course = Course.objects.get(pk=course_id)
student = Student.objects.create(name=name, email=email,
course=course)
return JsonResponse({'success': True})
return JsonResponse({'success': False})
Create a registration.html template in the
enrollment_app/templates/enrollment_app directory:
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Student Registration</h1>
<form id="registration-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="course">Course:</label>
<select id="course" name="course" required>
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name
}}</option>
{% endfor %}
</select><br>
<button type="submit">Register</button>
</form>
<div id="message"></div>
<script>
$(document).ready(function() {
$('#registration-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',
data: $(this).serialize(),
success: function(response) {
if (response.success) {
$('#message').text('Registration successful!');
$('#registration-form')[0].reset();
} else {
$('#message').text('Error: Registration failed.');
} } }); }); });
</script>
</body>
</html>
Step 3: Define URL patterns and include them in the project's URLs:
Define URL patterns in enrollment_app/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.registration_page, name='registration_page'),
path('register/', views.register_student, name='register_student'),]
Include these URLs in the project's urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('enrollment/', include('enrollment_app.urls')),]
Step 4: Run migrations and start the server: Apply migrations to create
database tables for the models and start the Django development server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Now, you can access the registration page at
http://127.0.0.1:8000/enrollment/ and register students without
page refresh using AJAX. The form will submit the data
asynchronously, and the success or error message will be displayed
without reloading the entire page.
OR
a) Discuss how the setting of Java script in Django.
For the development server, putting static content, including images, CSS,
and static content, is straightforward. For production use, the recommended
best practice is to use a different implementation, and Django users are
advised to use a separate server if possible, optimized for serving static
media, such as a stripped-down build of Apache. However, for development
use, the following steps will serve up static content:
1. Create a directory named static within your project. (Note that other
names may be used, but do not use media, as that can collide with
administrative tools.)
2. Edit the settings.py file, and add the following at the top, after import os:
DIRNAME = os.path.abspath(os.path.dirname(_file_))
MEDIA_URL = '/static/'
if settings.DEBUG:
urlpatterns += patterns('django.views.static',(r'^%s(?P<path>.*)$' %
(settings.MEDIA_URL[1:],),'serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes': True }),)
This will turn off static media service when DEBUG is turned off, so that
this code does not need to be changed when your site is deployed live, but
the subdirectory static within your project should now serve up static
content, like a very simplified Apache. We suggest that you create three
subdirectories of static: static/css,static/images, and static/js, for serving up
CSS, image, and JavaScript static content.
Step 1: Set up the Django app and models: First, create a Django app for
the search application:
python manage.py startapp search_app
Define the models for Course and Student in
search_app/models.py:
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course)
def __str__(self):
return self.name
Step 2: Create views and templates: Define views and templates to handle
the search functionality and display the results. In search_app/views.py,
create a view for handling the search request:
from django.shortcuts import render
from .models import Student
def search_courses(request):
if request.method == 'GET' and 'student_name' in request.GET:
student_name = request.GET['student_name']
student =
Student.objects.filter(name__icontains=student_name).first()
if student:
courses = student.courses.all()
else:
courses = []
return render(request, 'search_app/course_list.html', {'courses':
courses})
return render(request, 'search_app/search_form.html')
Create two HTML templates in the
search_app/templates/search_app directory:
search_form.html for the search form.
course_list.html for displaying the list of courses.
search_form.html:
<!DOCTYPE html>
<html>
<head>
<title>Search Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
"></script>
</head>
<body>
<h1>Search for Courses by Student Name</h1>
<form id="searchForm" method="GET">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="student_name">
<button type="submit">Search</button>
</form>
<div id="courseList"></div>
<script>
$(document).ready(function() {
$('#searchForm').on('submit', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '{% url "search_courses" %}',
type: 'GET',
data: formData,
success: function(response) {
$('#courseList').html(response);
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
} }); }); });
</script>
</body>
</html>
course_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Course List</title>
</head>
<body>
<h2>Courses Enrolled by {{ student.name }}</h2>
<ul>
{% for course in courses %}
<li>{{ course.name }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 3: Update URLs: Define URL patterns in search_app/urls.py to map
views to URLs:
from django.urls import path
from . import views
urlpatterns = [
path('', views.search_courses, name='search_courses'),]
Include these URLs in the project's urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('search/', include('search_app.urls')),]
Step 4: Run migrations and start the server: Apply migrations to create
database tables for the models and start the Django development server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Now, you can access the search form in your browser at
http://127.0.0.1:8000/search/ and search for courses enrolled by a
student by entering their name. The results will be displayed using
AJAX without refreshing the page