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 all Tasks #9

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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 title %}
<title>Login</title>
{% endblock %}

{% block content %}
<h2>Login</h2>
<br>
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button style="background-color:blue; color:white" class="btn btn-outline-info" type="submit">Login</button>
</form>
</div>
{% endblock %}
17 changes: 17 additions & 0 deletions authentication/templates/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{% extends "store/base.html" %}

{% block title %}
<title>Register</title>
{% endblock %}

{% block content %}
<h2>Register</h2>
<br>
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button style="background-color:blue; color:white" class="btn btn-outline-info" type="submit">Register</button>
</form>
</div>
{% endblock %}
8 changes: 8 additions & 0 deletions authentication/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path
from authentication.views import *

urlpatterns = [
path("login/", loginView, name="loginView"),
path("register/", registerView, name="register"),
path("logout/", logoutView, name="logout"),
]
46 changes: 41 additions & 5 deletions authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,49 @@
from django.shortcuts import render
from django.contrib.auth import login,logout,authenticate
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth import login,logout,authenticate
from django.contrib import messages
from library.forms import NewUserForm
# Create your views here.


def loginView(request):
pass
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("index")
else:
messages.error(request, "Invalid username or password.")
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})

def logoutView(request):
pass
logout(request)
messages.info(request, "Logged out successfully!")
return redirect("index")

def registerView(request):
pass
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"New Account Created: {username}")
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("index")

else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")

form = NewUserForm
return render(request, 'register.html', {'form': form})
17 changes: 17 additions & 0 deletions library/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)

class Meta:
model = User
fields = ("username", "email", "password1", "password2")

def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
17 changes: 2 additions & 15 deletions library/urls.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,12 @@
"""library URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
path('',include('store.urls')),
path('', include('authentication.urls')),
path('admin/', admin.site.urls),
path('authentication/',include('django.contrib.auth.urls')),
path('accounts/',include('django.contrib.auth.urls')),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
35 changes: 35 additions & 0 deletions store/migrations/0003_auto_20210720_1844.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Generated by Django 2.2.1 on 2021-07-20 13:14

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


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('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),
),
migrations.CreateModel(
name='UserRating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.FloatField(default=0)),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='store.Book')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='user', to=settings.AUTH_USER_MODEL)),
],
),
]
19 changes: 19 additions & 0 deletions store/migrations/0004_auto_20210721_1554.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 2.2.1 on 2021-07-21 10:24

from django.conf import settings
from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('store', '0003_auto_20210720_1844'),
]

operations = [
migrations.RenameModel(
old_name='UserRating',
new_name='BookRating',
),
]
8 changes: 8 additions & 0 deletions store/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,11 @@ def __str__(self):
else:
return f'{self.book.title} - Available'

class BookRating(models.Model):
user=models.ForeignKey(User, related_name='user', null=True, blank=True, on_delete=models.SET_NULL)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
rating = models.FloatField(default=0.0)

def __str__(self):
return f'{self.book.title}'

12 changes: 10 additions & 2 deletions store/templates/store/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@
<ul class="sidebar-nav">
{% if user.is_authenticated %}
<li>User: {{ user.first_name }}</li>
<li><a href="{% url 'view-loaned' %}">My Borrowed</a></li>
<li><a href="{% url 'view-loaned' %}">Borrowed Books</a></li>
<li><a href="{% url 'logout' %}">Logout</a></li>
{% else %}
<!-- <li><a href="{% url 'login'%}">Login</a></li> -->
<li><a href="{% url 'loginView' %}">Login</a></li>
<li><a href="{% url 'register' %}">Register</a></li>
{% endif %}
</ul>

Expand All @@ -42,5 +43,12 @@
</div>

</div>
{% if messages %}
<div class="alert alert-info" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
</body>
</html>
53 changes: 53 additions & 0 deletions store/templates/store/book_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,32 @@ <h2>Title: {{ book.title }}</h2>
<dd>Rs. {{ book.mrp }}</dd>
<dt>Available Copies:</dt>
<dd>{{ num_available }}</dd>
{% if user.is_authenticated %}
<dt>
<span>Rate: </span>
<span class="dropdown">
{% csrf_token %}
<select name="rating" id="ratingValue">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<button class="btn btn-success btn-sm" id="submitRating">Submit Rating</button>
</span>
</dt>
</dl>

<button class="btn btn-primary" id="loan-button">Loan {{ book.title }}</button>
{% else %}
<p>Please <a href="{% url 'loginView' %}">login</a> or <a href="{% url 'register' %}">register</a> to issue the book</p>
{% endif %}
<script>
$("#loan-button").click(function(){
$.ajax({
Expand All @@ -45,5 +69,34 @@ <h2>Title: {{ book.title }}</h2>

})
})


$("#submitRating").click(function () {

var r = document.getElementById("ratingValue").selectedIndex;
rating = document.getElementById("ratingValue").options[r].value;

$.ajax({
url: "{% url 'rate-book' %}",
method: "POST",
data: {
bid: {{ book.id }},
rate:rating,
},
success: function (data, status, xhr) {
if (data['message'] == "success") {
alert("Book successfully rated");
window.location.replace("/books/");
}
else {
alert("Unable to rate this book");
}
},
error: function (xhr, status, err) {
alert("Some error occured");
}

})
})
</script>
{% endblock %}
2 changes: 2 additions & 0 deletions store/templates/store/book_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
{% block content %}

<h3>Books list</h3>
<br>
<div class="row">
<div class="col-sm-3">
Title: <input type="text" name="title" id="title">
Expand All @@ -20,6 +21,7 @@ <h3>Books list</h3>
Genre: <input type="text" name="genre" id="genre">
</div>
</div>
<br>
<div class="row">
<button id="search_button" class="btn btn-primary">Search</button>
</div>
Expand Down
23 changes: 21 additions & 2 deletions store/templates/store/loaned_books.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,26 @@ <h3>Loaned Books list</h3>
<script>
// Fill in this function by yourself. It should make a post call to the returnBookView and display an appropriate message
function returnBook(bid){
;
}
$.ajax({
url: "{% url 'return-book' %}",
method: "POST",
data: {
'id': bid,
},
success: function(data, status, xhr){
if(data['message'] == "success"){
alert("Book successfully returned!");
window.location.replace("/books/loaned");
}
else{
alert("Unable to return this book");
}
},
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
Expand Up @@ -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('book/bookrating/', rateBookView, name="rate-book" )
]
Loading