0% found this document useful (0 votes)
1 views

Classroom Assignment 2

Uploaded by

Chandrakant Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Classroom Assignment 2

Uploaded by

Chandrakant Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Question 1: Write the steps leading to this code snippet:

from django.db import models

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
published_date = models.DateField()

def __str__(self):
return self.title

Question 2: Explain the code snippet:

1. from django import forms

# 1. Define a form for book submission


class BookForm(forms.Form):
title = forms.CharField(max_length=100, required=True)
author = forms.CharField(max_length=50, required=True)
published_date = forms.DateField(required=True)

2. from django.shortcuts import render


from .forms import BookForm

# 1. Define a view to handle form submissions


def submit_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
# 2. Process the form data
title = form.cleaned_data['title']
author = form.cleaned_data['author']
published_date = form.cleaned_data['published_date']
# Save the data to the database or perform other actions
else:
# 3. Display form with errors
return render(request, 'submit_book.html', {'form': form})
else:
form = BookForm()

return render(request, 'submit_book.html', {'form': form})

3. from django import forms

# 1. Define a customized form for book submission


class BookForm(forms.Form):
title = forms.CharField(
max_length=100,
widget=forms.TextInput(attrs={'placeholder': 'Enter book title'}),
label='Book Title'
)
author = forms.CharField(max_length=50, label='Author Name')
published_date = forms.DateField(widget=forms.SelectDateWidget)

# 2. Add custom validation for title


def clean_title(self):
title = self.cleaned_data['title']
if not title.isalpha():
raise forms.ValidationError('Title must contain only alphabetic characters.')
return title

4. from django.contrib import admin


from .models import Book

# 1. Register the Book model with the admin site


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
# 2. Customize the admin list display
list_display = ('title', 'author', 'published_date')
# 3. Add search functionality for title and author
search_fields = ('title', 'author__name')

You might also like