├── ratings ├── __init__.py ├── migrations │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── 0001_initial.cpython-38.pyc │ └── 0001_initial.py ├── tests.py ├── apps.py ├── admin.py ├── __pycache__ │ ├── admin.cpython-38.pyc │ ├── views.cpython-38.pyc │ ├── models.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── models.py ├── views.py └── templates │ └── ratings │ └── main.html ├── stars_proj ├── __init__.py ├── __pycache__ │ ├── urls.cpython-38.pyc │ ├── urls.cpython-39.pyc │ ├── wsgi.cpython-38.pyc │ ├── __init__.cpython-38.pyc │ ├── __init__.cpython-39.pyc │ ├── settings.cpython-38.pyc │ └── settings.cpython-39.pyc ├── asgi.py ├── wsgi.py ├── urls.py └── settings.py ├── db.sqlite3 ├── .vscode └── settings.json ├── media └── images │ ├── auto-788747_1280.jpg │ ├── m31-3613931_1280.jpg │ └── taxi-cab-381233_1280.jpg ├── static ├── style.css └── main.js ├── manage.py └── templates └── base.html /ratings/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stars_proj/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ratings/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ratings/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/db.sqlite3 -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": true, 3 | "python.linting.enabled": true 4 | } -------------------------------------------------------------------------------- /ratings/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class RatingsConfig(AppConfig): 5 | name = 'ratings' 6 | -------------------------------------------------------------------------------- /media/images/auto-788747_1280.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/media/images/auto-788747_1280.jpg -------------------------------------------------------------------------------- /media/images/m31-3613931_1280.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/media/images/m31-3613931_1280.jpg -------------------------------------------------------------------------------- /static/style.css: -------------------------------------------------------------------------------- 1 | .checked { 2 | color: red; 3 | } 4 | 5 | .my-btn { 6 | background-color: inherit !important; 7 | border: 0 !important; 8 | } -------------------------------------------------------------------------------- /media/images/taxi-cab-381233_1280.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/media/images/taxi-cab-381233_1280.jpg -------------------------------------------------------------------------------- /ratings/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Rating 3 | # Register your models here. 4 | 5 | admin.site.register(Rating) 6 | -------------------------------------------------------------------------------- /ratings/__pycache__/admin.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/__pycache__/admin.cpython-38.pyc -------------------------------------------------------------------------------- /ratings/__pycache__/views.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/__pycache__/views.cpython-38.pyc -------------------------------------------------------------------------------- /ratings/__pycache__/models.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/__pycache__/models.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/urls.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/urls.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/urls.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/urls.cpython-39.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/wsgi.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/wsgi.cpython-38.pyc -------------------------------------------------------------------------------- /ratings/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/settings.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/settings.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/__pycache__/settings.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/stars_proj/__pycache__/settings.cpython-39.pyc -------------------------------------------------------------------------------- /ratings/migrations/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/migrations/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /ratings/migrations/__pycache__/0001_initial.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Star-ratings-with-Django-and-Javascript/HEAD/ratings/migrations/__pycache__/0001_initial.cpython-38.pyc -------------------------------------------------------------------------------- /stars_proj/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for stars_proj project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stars_proj.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /stars_proj/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for stars_proj project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stars_proj.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /ratings/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.core.validators import MaxValueValidator, MinValueValidator 3 | # Create your models here. 4 | 5 | class Rating(models.Model): 6 | image = models.ImageField(upload_to='images/') 7 | score = models.IntegerField(default=0, 8 | validators=[ 9 | MaxValueValidator(5), 10 | MinValueValidator(0), 11 | ] 12 | ) 13 | 14 | def __str__(self): 15 | return str(self.pk) 16 | 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stars_proj.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /ratings/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from .models import Rating 3 | from django.http import JsonResponse 4 | # Create your views here. 5 | 6 | def main_view(request): 7 | obj = Rating.objects.filter(score=0).order_by("?").first() 8 | context ={ 9 | 'object': obj 10 | } 11 | return render(request, 'ratings/main.html', context) 12 | 13 | 14 | def rate_image(request): 15 | if request.method == 'POST': 16 | el_id = request.POST.get('el_id') 17 | val = request.POST.get('val') 18 | print(val) 19 | obj = Rating.objects.get(id=el_id) 20 | obj.score = val 21 | obj.save() 22 | return JsonResponse({'success':'true', 'score': val}, safe=False) 23 | return JsonResponse({'success':'false'}) -------------------------------------------------------------------------------- /ratings/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.1.2 on 2020-10-14 00:03 2 | 3 | import django.core.validators 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Rating', 17 | fields=[ 18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('image', models.ImageField(upload_to='images/')), 20 | ('score', models.IntegerField(default=0, validators=[django.core.validators.MaxValueValidator(5), django.core.validators.MinValueValidator(0)])), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /stars_proj/urls.py: -------------------------------------------------------------------------------- 1 | """stars_proj URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.conf import settings 19 | from django.conf.urls.static import static 20 | from ratings.views import main_view, rate_image 21 | 22 | urlpatterns = [ 23 | path('admin/', admin.site.urls), 24 | path('', main_view, name="main-view"), 25 | path('rate/', rate_image, name='rate-view'), 26 | ] 27 | 28 | urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 29 | urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Rating site | {% block title %}{% endblock title %} 18 | 19 | 20 |
21 | {% block content %} 22 | {% endblock content %} 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /ratings/templates/ratings/main.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} 4 | rate now 5 | {% endblock title %} 6 | 7 | {% block content %} 8 | {% if object %} 9 |
10 |
11 | image to rate 12 | 13 |
14 |
15 |
16 | {% csrf_token %} 17 | 18 | 19 | 20 | 21 | 22 |
23 |
24 |
25 |
26 | 27 |
28 | {% else %} 29 |

No images to rate

30 | {% endif %} 31 | 32 | {% endblock content %} -------------------------------------------------------------------------------- /stars_proj/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for stars_proj project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.1.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.1/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'afe^0z#39aswg5&y&z3^-4(k85x4qh!*ocp8l)qn3aniejy3o3' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'ratings', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'stars_proj.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [BASE_DIR / 'templates'], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'stars_proj.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.1/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.1/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.1/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | STATICFILES_DIRS = [ BASE_DIR / 'static'] 124 | 125 | MEDIA_URL = '/media/' 126 | MEDIA_ROOT = BASE_DIR / 'media' 127 | -------------------------------------------------------------------------------- /static/main.js: -------------------------------------------------------------------------------- 1 | // console.log('hello world') 2 | 3 | // get all the stars 4 | const one = document.getElementById('first') 5 | const two = document.getElementById('second') 6 | const three = document.getElementById('third') 7 | const four = document.getElementById('fourth') 8 | const five = document.getElementById('fifth') 9 | 10 | // get the form, confirm-box and csrf token 11 | const form = document.querySelector('.rate-form') 12 | const confirmBox = document.getElementById('confirm-box') 13 | const csrf = document.getElementsByName('csrfmiddlewaretoken') 14 | 15 | const handleStarSelect = (size) => { 16 | const children = form.children 17 | console.log(children[0]) 18 | for (let i=0; i < children.length; i++) { 19 | if(i <= size) { 20 | children[i].classList.add('checked') 21 | } else { 22 | children[i].classList.remove('checked') 23 | } 24 | } 25 | } 26 | 27 | const handleSelect = (selection) => { 28 | switch(selection){ 29 | case 'first': { 30 | // one.classList.add('checked') 31 | // two.classList.remove('checked') 32 | // three.classList.remove('checked') 33 | // four.classList.remove('checked') 34 | // five.classList.remove('checked') 35 | handleStarSelect(1) 36 | return 37 | } 38 | case 'second': { 39 | handleStarSelect(2) 40 | return 41 | } 42 | case 'third': { 43 | handleStarSelect(3) 44 | return 45 | } 46 | case 'fourth': { 47 | handleStarSelect(4) 48 | return 49 | } 50 | case 'fifth': { 51 | handleStarSelect(5) 52 | return 53 | } 54 | default: { 55 | handleStarSelect(0) 56 | } 57 | } 58 | 59 | } 60 | 61 | const getNumericValue = (stringValue) =>{ 62 | let numericValue; 63 | if (stringValue === 'first') { 64 | numericValue = 1 65 | } 66 | else if (stringValue === 'second') { 67 | numericValue = 2 68 | } 69 | else if (stringValue === 'third') { 70 | numericValue = 3 71 | } 72 | else if (stringValue === 'fourth') { 73 | numericValue = 4 74 | } 75 | else if (stringValue === 'fifth') { 76 | numericValue = 5 77 | } 78 | else { 79 | numericValue = 0 80 | } 81 | return numericValue 82 | } 83 | 84 | if (one) { 85 | const arr = [one, two, three, four, five] 86 | 87 | arr.forEach(item=> item.addEventListener('mouseover', (event)=>{ 88 | handleSelect(event.target.id) 89 | })) 90 | 91 | arr.forEach(item=> item.addEventListener('click', (event)=>{ 92 | // value of the rating not numeric 93 | const val = event.target.id 94 | 95 | let isSubmit = false 96 | form.addEventListener('submit', e=>{ 97 | e.preventDefault() 98 | if (isSubmit) { 99 | return 100 | } 101 | isSubmit = true 102 | // picture id 103 | const id = e.target.id 104 | // value of the rating translated into numeric 105 | const val_num = getNumericValue(val) 106 | 107 | $.ajax({ 108 | type: 'POST', 109 | url: '/rate/', 110 | data: { 111 | 'csrfmiddlewaretoken': csrf[0].value, 112 | 'el_id': id, 113 | 'val': val_num, 114 | }, 115 | success: function(response){ 116 | console.log(response) 117 | confirmBox.innerHTML = `

Successfully rated with ${response.score}

` 118 | }, 119 | error: function(error){ 120 | console.log(error) 121 | confirmBox.innerHTML = '

Ups... something went wrong

' 122 | } 123 | }) 124 | }) 125 | })) 126 | } 127 | --------------------------------------------------------------------------------