Commit 76997972 authored by Washington99's avatar Washington99

Added the "Add Book" functionality

The Book page now has an add book function where a new instance of a book entry maybe created in page. The page automatically redirects to the details page of the created entry upon successful creation.
parent 9299e990
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 13:45:10 2023
@author: user
"""
from .models import Author, Books
from django import forms
class BookForm(forms.ModelForm):
class Meta:
model = Books
fields = "__all__"
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Book</title>
</head>
<body>
{{ form.non_field_errors }}
{% for field in form %}
{% if field.errors %}
<p>{{ field.label }} has the following errors:</p>
<ul>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
<form act method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Add Book">
</form>
</body>
</html>
\ No newline at end of file
......@@ -23,7 +23,7 @@
</div>
<div>
<a href="">Add Author</a>
<a href="">Add Book</a>
<a href="/books/add">Add Book</a>
</div>
{% endblock %}
\ No newline at end of file
from django.urls import path
from .views import home_view, AuthorList, BookList, AuthorView, BookView
from .views import BooksCreateView
urlpatterns = [
path('home/', home_view, name = 'home_view'),
......@@ -7,6 +8,7 @@ urlpatterns = [
path('books/', BookList.as_view(), name = 'books'),
path('authors/<int:pk>/details/', AuthorView.as_view(), name = 'authors_details'),
path('books/<int:pk>/details/', BookView.as_view(), name = 'books_details'),
path('books/add/', BooksCreateView.as_view(), name = 'add-book'),
]
app_name = "bookshelf"
......
from django.shortcuts import render
from django.http.response import HttpResponseRedirect
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView
from .models import Author, Books
from .forms import BookForm
# Create your views here.
......@@ -24,4 +27,21 @@ class AuthorView(DetailView):
class BookView(DetailView):
model = Books
template_name = 'bookshelf/book_details.html'
class BooksCreateView(CreateView):
model = Books
form = BookForm
fields = '__all__'
template_name = 'bookshelf/add-book.html'
def post(self, request, *args, **kwargs):
form = BookForm(request.POST) # Create a Form object from the POST values
if form.is_valid():
new_book = form.save()
redirect_link = "../" + new_book.get_absolute_url() + "/details/"
return HttpResponseRedirect(redirect_link)
# return self.get(request, *args, **kwargs)
else:
return render(request, self.template_name, {'form': form})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment