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

All Tasks Completed #16

Open
wants to merge 4 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
12 changes: 12 additions & 0 deletions authentication/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30, help_text='Required')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
email = forms.EmailField(max_length=100, help_text='Enter a valid email-id')

class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
26 changes: 26 additions & 0 deletions authentication/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
{% block title %}
<title>Authentication</title>
{% endblock %}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- <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://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> -->
</head>

<body>
<div class="wrapper">
<div class="form col-xs-10 col-sm-12 col-md-7" style="display: flex; justify-content:center ">
{% block form %}
{% endblock %}
</div>
</div>
</body>
</html>
27 changes: 27 additions & 0 deletions authentication/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{% extends "base.html" %}
{% block title %}
<title>Login</title>
{% endblock %}

{% block form %}
<form action="{% url 'Login' %}" method="POST">
<h1 style="display: flex; justify-content:center;">Login</h1>
{% csrf_token %}
<div class="form-floating form-group mb-3">
<input type="text" class="form-control" id="username" name="Username" placeholder="Username" required>
<label for="floatingInput">Username</label>
</div>
<div class="form-floating form-group">
<input type="password" class="form-control" id="password" name="Password" placeholder="Password" required>
<label for="floatingPassword">Password</label>
</div>
<button type="login" class="btn btn-success mt-3 mb-2" value="Login">Login</button>
<div style="color: red; text-align: center;">
{% if message %}
{{message}}
{% endif %}
</div>
<h6>Don't have an account? <a href="{% url 'Register' %}">Register</a></h6>
<h6><a href="{% url 'book-list' %}">I just want to view the books</a></h6>
</form>
{% endblock %}
28 changes: 28 additions & 0 deletions authentication/templates/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{% extends "login.html" %}

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

{% block form %}
<form action="{% url 'Register' %}" method="POST">
<h1 style="display: flex; justify-content:center;">Register</h1>
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}
<br>
{{ field }}
{% if field.help_text %}
<small style="color: rgb(185, 185, 185);">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Register</button>
<h6>Already have an account? <a href="{% url 'Login' %}">Login</a></h6>
<h6><a href="{% url 'book-list' %}">I just want to view the books</a></h6>
</form>
{% 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,include
from authentication.views import *

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


def loginView(request):
pass
if request.user.is_authenticated:
return redirect('index')

if request.method == "POST":
data = request.POST
user = authenticate(request, username=data['Username'], password=data['Password'])
if user is not None:
login(request, user)
return redirect('index')
else:
return render(request, 'templates/login.html', {'message': "Username and/or password incorrect"})
else:
return render(request, 'templates/login.html')


def logoutView(request):
pass
logout(request)
return redirect('index')


def registerView(request):
pass
if request.user.is_authenticated:
return redirect('index')

if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
data = request.POST
new_user = User.objects.create_user(data['username'], data['email'], data['password1'])
new_user.first_name = data['first_name']
new_user.last_name = data['last_name']
new_user.save()
login(request, new_user)
return redirect('index')
else:
return render(request, 'templates/register.html', {'form': form})
else:
return render(request, 'templates/register.html', {'form': RegisterForm()})
4 changes: 2 additions & 2 deletions library/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'authentication/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down Expand Up @@ -108,7 +108,7 @@

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

Expand Down
4 changes: 2 additions & 2 deletions library/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from django.conf import settings

urlpatterns = [
path('',include('store.urls')),
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
Expand Up @@ -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_20210720_1757.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 2.2.1 on 2021-07-20 12:27

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),
),
]
26 changes: 26 additions & 0 deletions store/migrations/0004_bookrating.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 2.2.1 on 2021-07-22 12:42

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


class Migration(migrations.Migration):

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

operations = [
migrations.CreateModel(
name='BookRating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='store.Book')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
8 changes: 8 additions & 0 deletions store/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
# Create your models here.

class Book(models.Model):
Expand Down Expand Up @@ -30,3 +31,10 @@ def __str__(self):
else:
return f'{self.book.title} - Available'

class BookRating(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(default=None, validators=[MinValueValidator(0), MaxValueValidator(10)])
Copy link
Member

Choose a reason for hiding this comment

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

Great use of validators here.


def __str__(self):
return f'{self.book.title} - Rated {self.rating} by {self.user}'
3 changes: 2 additions & 1 deletion store/templates/store/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
<li><a href="{% url 'view-loaned' %}">My Borrowed</a></li>
<li><a href="{% url 'logout' %}">Logout</a></li>
{% else %}
<!-- <li><a href="{% url 'login'%}">Login</a></li> -->
<li><a href="{% url 'Login'%}">Login</a></li>
<li><a href="{% url 'Register'%}">Register</a></li>
{% endif %}
</ul>

Expand Down
40 changes: 38 additions & 2 deletions store/templates/store/book_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ <h2>Title: {{ book.title }}</h2>
<dd>Rs. {{ book.mrp }}</dd>
<dt>Available Copies:</dt>
<dd>{{ num_available }}</dd>
{% if user.is_authenticated %}
{% if current_user_rated is None %}
<dt>Rate Book:</dt>
{% else %}
<dt>Update Rating:</dt>
{% endif %}
<dd>
<input id="rating" type="number" min=0 max=10 value={{current_user_rated.rating}}>
<button class="btn btn-success" id= "rate-button" onclick="rateBook({{ book.id }})">Rate</button>
</dd>
{% endif %}
</dl>
<button class="btn btn-primary" id="loan-button">Loan {{ book.title }}</button>
<script>
Expand All @@ -40,10 +51,35 @@ <h2>Title: {{ book.title }}</h2>
}
},
error: function(xhr, status, err){
alert("Some error occured");
alert("Some error occured. Make sure you are logged in before borrowing a book.");
window.location.replace("/login");
}

})
})

function rateBook(bid){
const rating = document.getElementById("rating").value
$.ajax({
url: "{% url 'rate-book'%}",
method:"POST",
data:{
bid: bid,
rating: rating,
},
success: function(data, status, xhr){
if(data['message'] == "success"){
alert('Thanks for rating!');
location.reload();
}
else{
var msg = data['message'];
alert(msg);
}
},
error: function(xhr, status, err){
alert('Some error occured while rating the book!');
}
})
}
</script>
{% endblock %}
20 changes: 19 additions & 1 deletion store/templates/store/loaned_books.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,25 @@ <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: {
'bid': bid,
},
success: function(data, status, xhr){
if(data['message'] == "success"){
alert("Book successfully returned!");
location.reload();
}
else{
alert(data['message']);
}
},
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/rate/', rateBookView, name='rate-book'),
]
Loading