Commit a4abc98f authored by Gab De Jesus's avatar Gab De Jesus

Added prof search, review from specific prof page, review from index

parent 2fd277c4
...@@ -28,17 +28,22 @@ from courses import views as courses_views ...@@ -28,17 +28,22 @@ from courses import views as courses_views
from academe import views as academe_views from academe import views as academe_views
urlpatterns = [ urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^signup/$', accounts_views.signup, name='signup'), url(r'^signup/$', accounts_views.signup, name='signup'),
url(r'^account_activation_sent/$', accounts_views.account_activation_sent, name='account_activation_sent'), url(r'^account_activation_sent/$', accounts_views.account_activation_sent, name='account_activation_sent'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
accounts_views.activate, name='activate'), accounts_views.activate, name='activate'),
url(r'^login/$', auth_views.LoginView.as_view(template_name='templates/login.html'), name='login'), url(r'^login/$', auth_views.LoginView.as_view(template_name='templates/login.html'), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
url(r'^admin/', admin.site.urls),
url(r'^$', academe_views.index, name="homepage"), url(r'^$', academe_views.index, name="homepage"),
url(r'search/$', academe_views.search, name="search"),
url(r'browse/$', academe_views.show_courses_and_profs, name="browse"),
url(r'review/$', academe_views.review, name="review"),
url(r'review/(?P<prof_id>[0-9]+)/$', academe_views.review, name="review_prof"),
url(r'reviews/$', reviews_views.index, name="reviews_index"), url(r'reviews/$', reviews_views.index, name="reviews_index"),
url(r'^prof/$', profs_views.index, name="profs_index"), url(r'^prof/$', profs_views.index, name="profs_index"),
url(r'^prof/(?P<prof_id>[0-9]+)/$', profs_views.getProf, name="profs_getProf"), url(r'^prof/(?P<prof_id>[0-9]+)/$', profs_views.getProf, name="profs_getProf"),
url(r'^course/$', courses_views.index, name="courses_index"), url(r'^course/$', courses_views.index, name="courses_index"),
url(r'^course/prof/(?P<prof_name>[A-Za-z ]+)/$', courses_views.json_prof_courses, name="courses_json_prof_courses"),
# url(r'^course/(?P<course_id>[0-9]+)/$', courses_views.getCourse, name="courses_getCourse"), # url(r'^course/(?P<course_id>[0-9]+)/$', courses_views.getCourse, name="courses_getCourse"),
] ]
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from django.urls import reverse from django.urls import reverse
from django.http import HttpResponse
from django.db.models.functions import Concat
from django.db.models import Value
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from courses import views as course_views
from profs import views as prof_views
from reviews.forms import ReviewForm
from profs.models import Prof from profs.models import Prof
from profs.forms import ProfForm from django.contrib.auth.models import User
# Homepage
def index(request): def index(request):
# if(request.method=='POST'): """Landing page, contains the prof and course search"""
# form = ProfForm(request.POST) return render(request, 'templates/index.html')
# if(form.is_valid()):
# form.save() def show_courses_and_profs(request):
# # Return to profs_index using reverse so only need to change url in settings.py """
# return redirect(reverse('profs_index')) Shows all of the courses, and the profs under them.
Interfaces with the prof and course apps, to get
# profs = Prof.objects.all() the data from them
# return render(request, 'profs/index.html', {'prof_form':ProfForm, 'profs': profs}) """
return render(request, 'templates/index.html') courses = course_views.all_courses(request)
\ No newline at end of file return render(request, 'templates/browse.html', {'courses': courses})
def search(request):
""" Search function """
if(request.method == 'POST'):
prof_query = request.POST.get('prof', None)
course_query = request.POST.get('course', None)
try:
# Query profs
prof_set = Prof.objects.annotate(search_name=Concat('first_name', Value(' '), 'last_name'))
profs = prof_set.filter(search_name__icontains=prof_query)
# profs = Prof.objects.filter(first_name__icontains=prof_query last_name__contains=prof_query)
return render(request, 'profs/index.html', {'profs': profs})
except Prof.DoesNotExist:
return HttpResponse('No such prof')
else:
courses = course_views.all_course()
return render(request, 'templates/browse.html', {'courses': courses})
@login_required
def review(request, prof_id=None):
""" Review a prof """
if(request.method=='POST'):
# Insert the current user, and the prof with the id
# Happens when review is made through Review
post_values = request.POST.copy()
if prof_id:
post_values['prof'] = prof_id
post_values['user'] = request.user.id
print(post_values)
form = ReviewForm(post_values)
if(form.is_valid()):
form.save()
prof_id = post_values['prof']
return redirect(reverse('profs_getProf', args=(prof_id)))
else:
messages.error(request, "Error")
return render(request, 'reviews/review_form.html')
# If there's an input prof, return review page for that prof
if prof_id:
user = User.objects.get(pk=request.user.id)
prof = prof_views.prof(prof_id)
course = prof.course_set.all()
data = {'user': user, 'prof': prof}
review_form = ReviewForm(initial=data)
review_form.fields['course'].queryset = course
curr_prof = True
return render(request, 'reviews/review_form.html', {'review_form': review_form, 'curr_prof': curr_prof, 'prof': prof})
review_form = ReviewForm()
return render(request, 'reviews/review_form.html', {'review_form': review_form})
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-16 10:04 # Generated by Django 1.11.5 on 2017-11-30 06:35
from __future__ import unicode_literals from __future__ import unicode_literals
from django.conf import settings from django.conf import settings
......
...@@ -7,15 +7,4 @@ ...@@ -7,15 +7,4 @@
<li><a href="">{{ course.name }}</a></li> <li><a href="">{{ course.name }}</a></li>
</ul> </ul>
{% endfor %} {% endfor %}
<!-- Form for making a new review -->
<h1>New Review</h1>
<form method="POST">
{% csrf_token %}
<p>{{ review_form.message }}</p>d
<p>{{ review_form.rating }}</p>
<p>{{ review_form.prof }}</p>
<button type="submit">Save</button>
</form>
{% endblock %} {% endblock %}
\ No newline at end of file
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core import serializers
from django.urls import reverse from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.db.models.functions import Concat
from django.db.models import Value
from django.contrib import messages
import json
from profs.models import Prof from profs.models import Prof
from profs.forms import ProfForm
from .models import Course from .models import Course
from django.contrib import messages
from django.contrib.auth.models import User from django.contrib.auth.models import User
from reviews.models import Review from reviews.models import Review
from profs.forms import ProfForm
from reviews.forms import ReviewForm from reviews.forms import ReviewForm
from django.contrib.auth.decorators import login_required
def index(request): def index(request):
"""Show all the courses""" """Show all the courses"""
courses = Course.objects.all() courses = all_courses()
return render(request, 'courses/index.html', {'courses': courses}) return render(request, 'courses/index.html', {'courses': courses})
def all_courses(request):
"""Returns all the courses in the database"""
courses = Course.objects.all()
return courses
def prof_courses(request, prof_id):
""" Return the courses of a specific prof"""
course = Course.objects.filter(prof=prof_id)
return course
def json_prof_courses(request, prof_name):
""" Returns the JSON of courses of a specific prof for xhr"""
prof_set = Prof.objects.annotate(search_name=Concat('first_name', Value(' '), 'last_name'))
prof_id = prof_set.filter(search_name__icontains=prof_name)
courses = prof_courses(request, prof_id)
# Get all the courses
all_courses = {}
for course in courses:
all_courses[course.pk] = course.name
# data = serializers.serialize('json', all_courses)
data = json.dumps(all_courses)
return HttpResponse(data, content_type="application/json")
No preview for this file type
...@@ -4,7 +4,7 @@ from django.db import models ...@@ -4,7 +4,7 @@ from django.db import models
class Prof(models.Model): class Prof(models.Model):
first_name = models.CharField(max_length = 20, unique = False) first_name = models.CharField(max_length = 20, unique = False)
last_name = models.CharField(max_length = 20, unique = False) last_name = models.CharField(max_length = 20, unique = False)
def __str__ (self): def __str__ (self):
return self.first_name + " " + self.last_name return self.first_name + " " + self.last_name
...@@ -7,24 +7,4 @@ ...@@ -7,24 +7,4 @@
<li><a href="{% url 'profs_getProf' prof_id=prof.id %}">{{ prof.first_name}} {{ prof.last_name }}</a></li> <li><a href="{% url 'profs_getProf' prof_id=prof.id %}">{{ prof.first_name}} {{ prof.last_name }}</a></li>
</ul> </ul>
{% endfor %} {% endfor %}
<!-- Form for making a new review -->
<h1>New Review</h1>
<form method="POST">
{% csrf_token %}
<p>{{ review_form.message }}</p>
<p>{{ review_form.rating }}</p>
<p>{{ review_form.prof }}</p>
<button type="submit">Save</button>
</form>
<!-- Make the form for uploading a new prof -->
<!-- <h1>New prof</h1>
<form method="POST">
{% csrf_token %}
{{ prof_form.as_p }}
<button type="submit">Save</button>
</form> -->
{% endblock %} {% endblock %}
\ No newline at end of file
...@@ -38,7 +38,9 @@ ...@@ -38,7 +38,9 @@
{% endfor %} {% endfor %}
{% endif %} {% endif %}
<div class="form-group"> <p><a href="{% url 'review_prof' prof_id=prof.id %}">Review {{ prof.first_name }} {{ prof.last_name }}</a></p>
<!-- <div class="form-group">
<label for="comment">Review {{ prof.first_name }} {{ prof.last_name }}</label> <label for="comment">Review {{ prof.first_name }} {{ prof.last_name }}</label>
<form method="POST"> <form method="POST">
{% csrf_token %} {% csrf_token %}
...@@ -47,7 +49,7 @@ ...@@ -47,7 +49,7 @@
<p>{{ review_form.course }}</p> <p>{{ review_form.course }}</p>
<button type="submit" class="btn btn-default">Submit Review</button> <button type="submit" class="btn btn-default">Submit Review</button>
</form> </form>
</div> </div> -->
{% endblock %} {% endblock %}
\ No newline at end of file
...@@ -11,15 +11,7 @@ from reviews.forms import ReviewForm ...@@ -11,15 +11,7 @@ from reviews.forms import ReviewForm
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
def index(request): def index(request):
# Make a prof # Make a request
# if(request.method=='POST'):
# form = ProfForm(request.POST)
# if(form.is_valid()):
# form.save()
# # Return to profs_index using reverse so only need to change url in settings.py
# return redirect(reverse('profs_index'))
# Make a new review
if(request.method=='POST'): if(request.method=='POST'):
post_values = request.POST.copy() post_values = request.POST.copy()
post_values['user'] = request.user.id post_values['user'] = request.user.id
...@@ -31,7 +23,7 @@ def index(request): ...@@ -31,7 +23,7 @@ def index(request):
prof_id = post_values['prof'] prof_id = post_values['prof']
return redirect(reverse('profs_getProf', args=(prof_id))) return redirect(reverse('profs_getProf', args=(prof_id)))
profs = Prof.objects.all() profs = all_profs()
return render(request, 'profs/index.html', {'review_form': ReviewForm, 'profs': profs}) return render(request, 'profs/index.html', {'review_form': ReviewForm, 'profs': profs})
# Display the page of a prof using id passed through url # Display the page of a prof using id passed through url
...@@ -53,4 +45,13 @@ def getProf(request, prof_id): ...@@ -53,4 +45,13 @@ def getProf(request, prof_id):
prof = Prof.objects.get(pk=prof_id) prof = Prof.objects.get(pk=prof_id)
reviews = Review.objects.filter(prof = prof) reviews = Review.objects.filter(prof = prof)
return render(request, 'profs/prof.html', {'review_form': ReviewForm, 'prof': prof, 'reviews': reviews}) return render(request, 'profs/prof.html', {'review_form': ReviewForm, 'prof': prof, 'reviews': reviews})
# return redirect(reverse('homepage'))
def all_profs():
"""Returns all the professors in the database"""
profs = Prof.objects.all()
return profs
def prof(pk):
"""Returns a prof object with specific id"""
prof = Prof.objects.get(pk=pk)
return prof
\ No newline at end of file
...@@ -11,4 +11,9 @@ class ReviewForm(ModelForm): ...@@ -11,4 +11,9 @@ class ReviewForm(ModelForm):
class Meta: class Meta:
model = Review model = Review
fields = ['message', 'rating', 'prof', 'course', 'user'] fields = ['message', 'rating', 'prof', 'course', 'user']
\ No newline at end of file
def __init__(self, *args, **kwargs):
super(ReviewForm, self).__init__(*args, **kwargs)
self.fields['prof'].widget.attrs['id'] = 'prof'
<!-- Make the form for uploading a new review -->
{% extends 'templates/base.html' %}
{% block content %}
<h1>New review {% if curr_prof %} for {{ prof.first_name }} {{ prof.last_name }}{% endif %}</h1>
<form method="POST">
{% csrf_token %}
<p>{{ review_form.message }}</p>
<p>{{ review_form.rating }}</p>
{% if not curr_prof %}
<!-- If no prof selected, show all profs and courses -->
<p>{{ review_form.prof }} <span id="show" style="display: none">Getting Courses...</span></p>
{% else %}
<p>{{ review_form.course }}</p>
{% endif %}
<button type="submit">Save</button>
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
<!-- AJAX -->
<script type="text/javascript">
var profDropDown = document.getElementById('prof');
function dropDownSelect() {
if(profDropDown.selectedIndex > 0) {
var profName = profDropDown.options[profDropDown.selectedIndex].text;
if(profName !== "") {
console.log("Getting courses of " + profName);
callXHR(profName);
}
}
}
function callXHR(profName) {
// Get the courses of the prof specified
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// If the drop down has been made, delete it
if (document.querySelector('#show ~ select')) {
var dropDown = document.querySelector('#show ~ select');
dropDown.remove();
}
// Make the dropdown
document.querySelector("#show").style.display = "inline";
var select = document.getElementById('show').parentNode;
select.append(document.createElement('select'));
var dropDown = document.querySelector('#show ~ select');
dropDown.name = 'course';
var json = JSON.parse(xhr.response);
// Add the courses returned by json to to the dropdown
for (var i = 1; course = json[i]; i++) {
if (i == 1) {
var placeholder = document.createElement('option');
placeholder.value = "";
placeholder.textContent = "Select a course";
dropDown.appendChild(placeholder);
}
var option = document.createElement('option');
option.value = i;
option.textContent = course;
dropDown.appendChild(option);
}
document.querySelector("#show").style.display = "none";
console.log("XHR Request done");
}
};
xhr.open("GET", "/course/prof/" + profName + '/', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
console.log('Sent XHR request for prof ' + profName);
}
document.getElementById('prof').addEventListener("change", dropDownSelect);
</script>
</form>
{% endblock %}
\ No newline at end of file
...@@ -13,11 +13,17 @@ ...@@ -13,11 +13,17 @@
<a class="navbar-brand" href="{% url 'homepage' %}">Academe</a> <a class="navbar-brand" href="{% url 'homepage' %}">Academe</a>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto"> <ul class="navbar-nav mr-auto">
<li class="nav-item"> <!-- <li class="nav-item">
<a class="nav-link" href="{% url 'profs_index' %}">Professors</a> <a class="nav-link" href="{% url 'profs_index' %}">Professors</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{% url 'course_index' %}">Courses</a> <a class="nav-link" href="{% url 'courses_index' %}">Courses</a>
</li> -->
<li class="nav-item">
<a class="nav-link" href="{% url 'browse' %}">Browse</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'review' %}">Review</a>
</li> </li>
</ul> </ul>
<form class="form-inline"> <form class="form-inline">
......
{% extends 'templates/base.html' %}
{% block content %}
<h1><center>Browse</center></h1>
{% for course in courses %}
<div class="course">
<h3 id="title"><center>{{ course.name }}</center></h3>
<ul style="text-align: center; list-style: none; padding: 0">
{% for prof in course.prof.all %}
<li class="prof"><center><a href="{% url 'profs_getProf' prof_id=prof.id %}">{{ prof.first_name }} {{ prof.last_name }}</a></center></li>
{% endfor %}
</ul>
</div>
{% endfor %}
<script type="text/javascript">
// Get all courses
var courses = document.getElementsByClassName('course');
var sorted_courses = [];
// Insert the course html into sorted_courses
for(i = 0; (course = courses[i]); i++) {
sorted_courses.push(course);
console.log(course.innerHTML);
}
// Sort by course title alphabetically
sorted_courses = sorted_courses.sort(function(a, b) {
var courseTitleA = a.getElementById('title').toLowerCase();
var courseTitleB = b.getElementById('title').toLowerCase();
if (courseTitleA < courseTitleB) return -1;
else if (courseTitleA > courseTitleB) return 1;
return 0;
});
for (var i = sorted_courses.length - 1; i >= 0; i--) {
console.log(sorted_courses[i]);
}
var imgs = document.getElementsByClassName('prof');
var i, img, sorted = [];
// Push each paragraphs text into sorted
for(i = 0; (img = imgs[i]); i++) {
sorted.push(img.innerText);
}
// Sort by alphabetical order
sorted = sorted.sort(function(a, b) {
var nameA = a.toLowerCase();
var nameB = b.toLowerCase();
if (nameA < nameB) return -1;
else if (nameA > nameB) return 1;
return 0;
});
for(i = 0; (img = imgs[i]); i++) {
// img.innerText = sorted[i];
}
for(i = 0; i < sorted.length; i++) {
// console.log(sorted[i]);
}
</script>
{% endblock %}
{% extends 'templates/base.html' %} {% extends 'templates/base.html' %}
{% block content %} {% block content %}
<h1><center>Welcome to Academe</center></h1> <h1><center>Welcome to Academe</center></h1>
<form method="post" action="/search/" style="text-align: center">
{% csrf_token %}
<div>
<input type="text" placeholder="Search a course" name="course">
<br>
<button class="btn btn-outline-success">Search Course</button>
</div>
<p>or</p>
<div>
<input type="text" placeholder="Search a prof" name="prof">
<br>
<button class="btn btn-outline-success">Search Prof</button>
</div>
<br>
</form>
{% endblock %} {% endblock %}
\ No newline at end of file
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