I am writing a book database, and ultimately a library system, in Django. When a book is created without a title set, the ISBN will be used to automatically fetch book data from WorldCat I have just created a form to add new books to the database, but it has no real error-handling. Also, as I am new to Django, I suspect I have put a lot of my code in the wrong place.
Improving error-handling is my main incentive, but any other improvements would be welcome.
The form, in forms.py:
class AddBookForm(ModelForm):
"""docstring for AddBookForm"""
class Meta:
model = Book
fields = ['isbn']
The form view, in views.py:
# This defines the navbar
pages = [['Search', '/'], ['Add Book', '/add']]
def add_book(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = AddBookForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
addedBook = form.save()
# if a GET (or any other method) we'll create a blank form
else:
form = AddBookForm()
# Highlights navbar entry
pages[1].append(True)
context = {'pages': pages, 'form': form,}
if 'addedBook' in locals():
context['added'] = addedBook
else:
context['added'] = None
return render(request, 'library/add.html', context)
The form template (add.html):
{% extends "library/base_site.html" %}
{% block title %}Add book{% endblock %}
{% block content %}
{% if added %}
<div class="alert alert-success" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
Succesfully added book "{{ added.title }}" by {{ added.author }} - ISBN {{ added.isbn }}
</div>
{% endif %}
<form role="form" method="post" action=".">
{% csrf_token %}
<div class="form-group">
<label for="id_isbn">Isbn</label>
<input id="id_isbn" class="form-control" maxlength="13" name="isbn" type="text" placeholder="Enter ISBN or scan barcode">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% endblock %}
The entire project is available on GitHub.