Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed The Tasks!!! #4

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions authentication/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{% extends "store/base.html" %}

{% block content %}
<div class="alert alert-success" role="alert" style="display:{{visibility}};">
<strong>Thanks for choosing us!</strong> Login again for full features.
</div>
<form class="inputform bg-primary mt-3" method="post" action="/login">
{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Please Login</h1>
<label for="inputusername" class="sr-only">Username</label>
<input type="text" id="inputusername" name="username" class="form-control mb-3" placeholder="Username" required
autofocus>
<label for="inputpassword" class="sr-only">Password</label>
<input type="password" id="inputpassword" name="password" class="form-control mb-3" placeholder="Password" required>
<button class="btn btn-lg btn-success " type="submit">Sign in</button>
</form>
{% endblock content %}
23 changes: 23 additions & 0 deletions authentication/templates/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{% extends "store/base.html" %}

{% block content %}
<div class="alert alert-danger mt-0 mb-0" role="alert" style="display:{{visibility}};">
<strong>Same credentials are in database!</strong> Login using it.
</div>
<form class="inputform bg-primary mt-3" method="post" action="/register">
{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Please Register</h1>
<label for="name" class="sr-only">Name</label>
<input type="text" id="inputName" name="name" class="form-control mb-3 " placeholder="Name" required
autofocus>
<label for="username" class="sr-only">Username</label>
<input type="text" id="inputUsername" name="username" class="form-control mb-3 " placeholder="Username" required
autofocus>
<label for="email" class="sr-only">Email</label>
<input type="email" id="inputEmail" name="email" class="form-control mb-3 " placeholder="Email" required
autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="password" class="form-control mb-3 " placeholder="Password" required>
<button class="btn btn-lg btn-success btn-block" type="submit">Register</button>
</form>
{% endblock content %}
9 changes: 9 additions & 0 deletions authentication/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.contrib import admin
from django.urls import path, include
from authentication.views import *

urlpatterns = [
path('login',loginView, name="login"),
path('logout',logoutView, name="logout"),
path('register',registerView, name="register"),
]
46 changes: 42 additions & 4 deletions authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,51 @@
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.models import User
# Create your views here.


def loginView(request):
pass
context={
"visibility":"none",
}
if request.method=="POST":
username= request.POST.get('username')
password= request.POST.get('password')
user = authenticate(username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect("/")
else:
return render(request, 'login.html',context)
return render(request, 'login.html',context)

def logoutView(request):
pass
logout(request)
context={
'visibility':"",
}
return render(request, 'login.html',context)

def registerView(request):
pass
context={
'visibility':"none",
}
if request.method=="POST":
name = request.POST.get('name')
username= request.POST.get('username')
email = request.POST.get('email')
password= request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
context['visibility']=""
return render(request, 'register.html',context)
user = User.objects.create_user(username,email,password)
user.first_name=name
if user is not None:
user.save()
login(request, user)
return redirect("/")
else:
return render(request, 'register.html',context)
return render(request, 'register.html',context)
2 changes: 1 addition & 1 deletion library/settings.py
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@
SECRET_KEY = '==e^87*tib$+f)9$46#-jc&toydks5v^g5ym7wq^shf5(hno3&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = False

ALLOWED_HOSTS = []

1 change: 1 addition & 0 deletions library/urls.py
Original file line number Diff line number Diff line change
@@ -20,6 +20,7 @@

urlpatterns = [
path('',include('store.urls')),
path('', include('authentication.urls')),
path('admin/', admin.site.urls),
path('accounts/',include('django.contrib.auth.urls')),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
1 change: 1 addition & 0 deletions store/admin.py
Original file line number Diff line number Diff line change
@@ -4,3 +4,4 @@

admin.site.register(Book)
admin.site.register(BookCopy)
admin.site.register(BookRating)
25 changes: 25 additions & 0 deletions store/migrations/0003_auto_20210718_0608.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 2.2.1 on 2021-07-18 06:08

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('store', '0002_auto_20190607_1302'),
]

operations = [
migrations.AlterField(
model_name='bookcopy',
name='borrow_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='bookcopy',
name='borrower',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='borrower', to=settings.AUTH_USER_MODEL),
),
]
23 changes: 23 additions & 0 deletions store/migrations/0004_bookrating.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 2.2.1 on 2021-07-18 14:33

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('store', '0003_auto_20210718_0608'),
]

operations = [
migrations.CreateModel(
name='BookRating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rater', models.CharField(max_length=122)),
('rated', models.SmallIntegerField(default=0)),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='store.Book')),
],
),
]
23 changes: 23 additions & 0 deletions store/migrations/0005_auto_20210718_1529.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 2.2.1 on 2021-07-18 15:29

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('store', '0004_bookrating'),
]

operations = [
migrations.AddField(
model_name='bookrating',
name='rating',
field=models.SmallIntegerField(default=0),
),
migrations.AlterField(
model_name='bookrating',
name='rated',
field=models.BooleanField(default=False),
),
]
7 changes: 7 additions & 0 deletions store/models.py
Original file line number Diff line number Diff line change
@@ -30,3 +30,10 @@ def __str__(self):
else:
return f'{self.book.title} - Available'

class BookRating(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
rater = models.CharField(max_length=122)
rated = models.BooleanField(default = False)
rating = models.SmallIntegerField(default=0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also use MinValueValidator, `MaxValueValidator on this field to have database level rules for it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I'll take care of this from now onwards.

def __str__(self):
return f'{self.book.title} by {self.rater} : {self.rated}'
15 changes: 13 additions & 2 deletions store/templates/store/base.html
Original file line number Diff line number Diff line change
@@ -8,6 +8,16 @@
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<style>
.inputform{
width: fit-content;
margin: auto;
border: 2px solid black;
padding: 20px;
border-radius: 10px;
color: white;
}
</style>
{% load static %}
</head>

@@ -27,9 +37,10 @@
{% if user.is_authenticated %}
<li>User: {{ user.first_name }}</li>
<li><a href="{% url 'view-loaned' %}">My Borrowed</a></li>
<li><a href="{% url 'logout' %}">Logout</a></li>
<li><a href="/logout">Logout</a></li>
{% else %}
<!-- <li><a href="{% url 'login'%}">Login</a></li> -->
<li><a href="/login">Login</a></li>
<li><a href="/register">Register</a></li>
{% endif %}
</ul>

30 changes: 27 additions & 3 deletions store/templates/store/book_detail.html
Original file line number Diff line number Diff line change
@@ -22,6 +22,9 @@ <h2>Title: {{ book.title }}</h2>
<dd>{{ num_available }}</dd>
</dl>
<button class="btn btn-primary" id="loan-button">Loan {{ book.title }}</button>
<button class="btn btn-warning font-weight-bold" id="rate-button">Rate Now</button>
<label id = "setval" for="Rate" class="form-label font-weight-bold">5</label>
<input type="range" id="getval" class="form-range" onchange="changeval()" min="0" max="10" step="1.0" id="Rate">
<script>
$("#loan-button").click(function(){
$.ajax({
@@ -32,15 +35,36 @@ <h2>Title: {{ book.title }}</h2>
},
success: function(data, status, xhr){
if(data['message'] == "success"){
alert("Book successfully issued");
alert("Book successfully issued!");
window.location.replace("/books/loaned");
}
else{
alert("Unable to issue this book");
alert("Unable to issue this book!");
}
},
error: function(xhr, status, err){
alert("Some error occured");
alert("You are not logged in!");
}

})
})
function changeval(){
document.getElementById("setval").innerHTML=document.getElementById('getval').value;
}
$("#rate-button").click(function(){
$.ajax({
url: "{% url 'rate-book' %}",
method: "POST",
data: {
bid: {{ book.id }},
rate: document.getElementById('getval').value,
},
success: function(data, status, xhr){
alert(data['message']);
location.reload();
},
error: function(xhr, status, err){
alert("You are not logged in!");
}

})
7 changes: 7 additions & 0 deletions store/templates/store/book_list.html
Original file line number Diff line number Diff line change
@@ -45,6 +45,13 @@ <h3>Books list</h3>
<td>{{ book.mrp }}</td>
</tr>
{% endfor %}
{% if books %}
{% else %}
<tr>
<th></th>
<td><strong>Nothing found!</strong></td>
</tr>
{% endif %}
</tbody>
</table>
<script>
24 changes: 22 additions & 2 deletions store/templates/store/loaned_books.html
Original file line number Diff line number Diff line change
@@ -32,12 +32,32 @@ <h3>Loaned Books list</h3>
<td><button class="btn btn-primary" onclick="returnBook({{ copy.id }})">Return {{ copy.book.title }}</button></td>
</tr>
{% endfor %}
{% if books %}
{% else %}
<tr>
<th></th>
<td><strong>Nothing issued!</strong></td>
</tr>
{% endif %}
</tbody>
</table>
<script>
// Fill in this function by yourself. It should make a post call to the returnBookView and display an appropriate message
function returnBook(bid){
;
function returnBook(bookid){
$.ajax({
url: "{% url 'return-book' %}",
method: "POST",
data: {
bid: bookid
},
success: function(data, status, xhr){
alert(data['message']);
window.location.replace("/books");
},
error: function(xhr, status, err){
alert("Some error occured");
}
})
}
</script>
{% endblock %}
1 change: 1 addition & 0 deletions store/urls.py
Original file line number Diff line number Diff line change
@@ -8,4 +8,5 @@
path('books/loaned/', viewLoanedBooks, name="view-loaned"),
path('books/loan/', loanBookView, name="loan-book"),
path('books/return/', returnBookView, name="return-book"),
path('books/rate/', rateBook, name="rate-book"),
]
83 changes: 70 additions & 13 deletions store/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404
from store.models import *
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from datetime import datetime
# from django.contrib.auth.models import User
# from django.contrib.auth import logout, authenticate, login
# Create your views here.

def index(request):
@@ -14,11 +16,18 @@ def bookDetailView(request, bid):
template_name = 'store/book_detail.html'
context = {
'book': None, # set this to an instance of the required book
'num_available': None, # set this to the number of copies of the book available, or 0 if the book isn't available
'num_available': 0, # set this to the number of copies of the book available, or 0 if the book isn't available
}
# START YOUR CODE HERE


get_data = request.GET
# START YOUR CODE HERE
context['book'] = Book.objects.filter(pk=bid)[0]
available=0
copies=BookCopy.objects.filter(book=context['book'])
for i in range(len(copies)):
if ((copies[i].__str__()).find('Available')!=-1): available=available+1
context['num_available'] = available
# print(BookCopy.objects.filter(book=context['book'])[2])
return render(request, template_name, context=context)


@@ -31,7 +40,11 @@ def bookListView(request):
}
get_data = request.GET
# START YOUR CODE HERE

books = Book.objects.all()
if(get_data.get('title')): books=books.filter(title=get_data.get('title'))
if(get_data.get('author')): books=books.filter(author=get_data.get('author'))
if(get_data.get('genre')): books=books.filter(genre=get_data.get('genre'))
context['books']=books

return render(request, template_name, context=context)

@@ -46,9 +59,7 @@ def viewLoanedBooks(request):
BookCopy model. Only those book copies should be included which have been loaned by the user.
'''
# START YOUR CODE HERE



context['books'] = BookCopy.objects.filter(borrower=request.user)
return render(request, template_name, context=context)

@csrf_exempt
@@ -62,9 +73,20 @@ def loanBookView(request):
If yes, then set the message to 'success', otherwise 'failure'
'''
# START YOUR CODE HERE
book_id = None # get the book id from post data


book_id = request.POST.get('bid') # get the book id from post data
book = Book.objects.filter(pk=book_id)[0]
bookcopy=BookCopy.objects.filter(book=book).filter(status=True)
if (len(bookcopy)):
bookcopy=bookcopy[0]
if(len(BookRating.objects.filter(book=book,rater=request.user.username))==0):
issuedbook = BookRating(book=book,rater=request.user.username)
issuedbook.save()
response_data['message'] = 'success'
bookcopy.borrower=request.user
bookcopy.borrow_date=datetime.today()
bookcopy.status=False
bookcopy.save()
else: response_data['message'] = 'failure'
return JsonResponse(response_data)

'''
@@ -77,6 +99,41 @@ def loanBookView(request):
@csrf_exempt
@login_required
def returnBookView(request):
pass
response_data = {
'message': "Book is successfully returned! Watch for more books.",
}
book_id = request.POST.get('bid') # get the book id from post data
book = Book.objects.filter(pk=book_id)[0]
bookcopy=BookCopy.objects.filter(book=book).filter(status=False)[0]
bookcopy.borrower=None
bookcopy.borrow_date=None
bookcopy.status=True
bookcopy.save()
return JsonResponse(response_data)

@csrf_exempt
@login_required
def rateBook(request):
response_data = {
'message': "Successfully rated!",
}
username =request.user.username
book_id = request.POST.get('bid') # get the book id from post data
book = Book.objects.filter(pk=book_id)[0]
newrating = BookRating.objects.filter(book=book,rater=username)
if(len(newrating)==0):
response_data['message']="You have not issued the book!"
return JsonResponse(response_data)
newrating=newrating[0]
rate = request.POST.get('rate')
newrating.rated=True
newrating.rating=rate
newrating.save()

bookratings=BookRating.objects.filter(book=book,rated=True)
sum=0.0
for i in range(len(bookratings)):
sum=sum+bookratings[i].rating
book.rating=round((float)(sum/len(bookratings)), 1)
Comment on lines +134 to +137
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is correct but a more clean and Django-ish way for this could be (with looping):

book.rating = BookRating.objects.filter(book__pk=book_id).aggregate(Avg('rating'))['rating__avg']

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I'll make sure to use these functions from next time.

book.save()
return JsonResponse(response_data)