From 293bd2d07d596f228fe7188cbf595d650fdf0244 Mon Sep 17 00:00:00 2001 From: iintii Date: Sat, 19 Jul 2025 11:15:26 -0400 Subject: [PATCH 01/36] Adding temporary changes to Github --- server/djangoproj/settings.py | 10 ++- server/djangoproj/urls.py | 2 + server/frontend/static/About.html | 122 ++++++++++++++-------------- server/frontend/static/Contact.html | 60 ++++++++++++++ 4 files changed, 130 insertions(+), 64 deletions(-) create mode 100644 server/frontend/static/Contact.html diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index e0b1092a5c..d15f94af5b 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -28,8 +28,8 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] -CSRF_TRUSTED_ORIGINS = [] +ALLOWED_HOSTS=['localhost','https://brody8991-8000.theianext-0-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai/'] +CSRF_TRUSTED_ORIGINS=['https://brody8991-8000.theianext-0-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai/'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [], @@ -61,7 +61,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [os.path.join(BASE_DIR,'frontend/static')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -134,5 +134,7 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -STATICFILES_DIRS = [] +STATICFILES_DIRS = [ + os.path.join(BASE_DIR,'frontend/static') +] diff --git a/server/djangoproj/urls.py b/server/djangoproj/urls.py index 6808da9141..e97a26491a 100644 --- a/server/djangoproj/urls.py +++ b/server/djangoproj/urls.py @@ -20,6 +20,8 @@ from django.conf import settings urlpatterns = [ + path('contact/', TemplateView.as_view(template_name="Contact.html")), + path('about/', TemplateView.as_view(template_name="About.html")), path('admin/', admin.site.urls), path('djangoapp/', include('djangoapp.urls')), path('', TemplateView.as_view(template_name="Home.html")), diff --git a/server/frontend/static/About.html b/server/frontend/static/About.html index 484efd960f..8e23c85877 100644 --- a/server/frontend/static/About.html +++ b/server/frontend/static/About.html @@ -1,68 +1,70 @@ - +      +   
- - -
- -
-
- Card image -
-

Person1

-

Person1 Title

-

Some text that explains the person1 in about 2 short sentences

-

person1@example.com

-
-
+  +   
+      +     
+     
+        Card image +       
+         

John Doe

+         

General Manager

+         

John has over 20 years of experience in the automotive industry and is dedicated to customer satisfaction. He leads our team with a passion for cars and a commitment to excellence.

+         

john.doe@example.com

+       
+     
-
- Card image -
-

Person2

-

Person2 Title

-

Some text that explains the person2 in about 2 short sentences

-

person2@example.com

-
-
+     
+        Card image +       
+         

Jane Smith

+         

Sales Director

+         

Jane excels at helping customers find their perfect vehicle. Her extensive knowledge of our inventory and friendly approach make the car-buying process a breeze.

+         

jane.smith@example.com

+       
+     
-
- Card image -
-

Person3

-

Person3 Title

-

Some text that explains the person3 in about 2 short sentences

-

person3@example.com

-
-
-
-
-
- +     
+        Card image +       
+         

Peter Jones

+         

Finance Manager

+         

Peter works tirelessly to secure the best financing options for our clients. He ensures a smooth and transparent process, making your dream car more affordable.

+         

peter.jones@example.com

+       
+     
+   
+   
+    +    - + \ No newline at end of file diff --git a/server/frontend/static/Contact.html b/server/frontend/static/Contact.html new file mode 100644 index 0000000000..612ea989a8 --- /dev/null +++ b/server/frontend/static/Contact.html @@ -0,0 +1,60 @@ + + +    Contact Us +    +    + + +   
+        +        +       
+            +           
+               
+                    Customer Service Icon +               
+               
+                   

Contact Customer Service

+                    support@bestcars.com +                   
+                   

Contact our National Advertising team

+                    NationalSales@bestcars.com +                   
+                   

Contact our Public Relations team

+                    PR@bestcars.com +                   
+                   

Contact the bestcars.com offices

+                   

312-611-1111

+                   
+                    Become a bestcars.com car dealer +                   
+                    Visit growwithbestcars.com +               
+           
+       
+   
+ + \ No newline at end of file From bb7d0a18fbacba8eec2214a8faa3287896b3e955 Mon Sep 17 00:00:00 2001 From: iintii Date: Sat, 19 Jul 2025 13:11:49 -0400 Subject: [PATCH 02/36] m --- server/frontend/package-lock.json | 30 +++++++++++++++++++++++++++--- server/frontend/static/Home.html | 23 +++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/server/frontend/package-lock.json b/server/frontend/package-lock.json index 0797425307..bdb21fad35 100644 --- a/server/frontend/package-lock.json +++ b/server/frontend/package-lock.json @@ -16,6 +16,9 @@ "react-router-dom": "^6.19.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" + }, + "devDependencies": { + "@babel/plugin-proposal-private-property-in-object": "^7.21.11" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -646,9 +649,18 @@ } }, "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "version": "7.21.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", + "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", + "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.18.6", + "@babel/helper-create-class-features-plugin": "^7.21.0", + "@babel/helper-plugin-utils": "^7.20.2", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, "engines": { "node": ">=6.9.0" }, @@ -1891,6 +1903,18 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", diff --git a/server/frontend/static/Home.html b/server/frontend/static/Home.html index fb0c3fb617..7086dcb951 100644 --- a/server/frontend/static/Home.html +++ b/server/frontend/static/Home.html @@ -23,6 +23,29 @@ 'Register' } } + + + // Build logout URL and Make GET request to logout endpoint + let logout_url = window.location.origin+"/djangoapp/logout"; + const res = await fetch(logout_url, { + method: "GET", + }); + + const json = await res.json(); + if (json) { + // Clear session storage and reload page + let username = sessionStorage.getItem('username'); + sessionStorage.removeItem('username'); + window.location.href = window.location.origin; + window.location.reload(); + // Notify user of logout + alert("Logging out "+username+"...") + } + else { + alert("The user could not be logged out.") + } + + From 50e7b8f67108c54fafa5c8620778dcf0382eba36 Mon Sep 17 00:00:00 2001 From: iintii Date: Sat, 19 Jul 2025 13:58:10 -0400 Subject: [PATCH 03/36] y --- server/frontend/src/App.js | 2 + .../src/components/Register/Register.jsx | 101 +++++++++++++ server/frontend/static/Home.html | 133 +++++++++--------- 3 files changed, 168 insertions(+), 68 deletions(-) create mode 100644 server/frontend/src/components/Register/Register.jsx diff --git a/server/frontend/src/App.js b/server/frontend/src/App.js index aceac6974d..2d4fb633bb 100644 --- a/server/frontend/src/App.js +++ b/server/frontend/src/App.js @@ -1,10 +1,12 @@ import LoginPanel from "./components/Login/Login" import { Routes, Route } from "react-router-dom"; +import Register from "./components/Register/Register"; function App() { return ( } /> + }/> ); } diff --git a/server/frontend/src/components/Register/Register.jsx b/server/frontend/src/components/Register/Register.jsx new file mode 100644 index 0000000000..d7981a606e --- /dev/null +++ b/server/frontend/src/components/Register/Register.jsx @@ -0,0 +1,101 @@ +import React, { useState } from "react"; +import "./Register.css"; +import user_icon from "../assets/person.png" +import email_icon from "../assets/email.png" +import password_icon from "../assets/password.png" +import close_icon from "../assets/close.png" + +const Register = () => { +// State variables for form inputs + const [userName, setUserName] = useState(""); + const [password, setPassword] = useState(""); + const [email, setEmail] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setlastName] = useState(""); + +// Redirect to home + const gohome = ()=> { + window.location.href = window.location.origin; + } + +// Handle form submission + const register = async (e) => { + e.preventDefault(); + + let register_url = window.location.origin+"/djangoapp/register"; + +// Send POST request to register endpoint + const res = await fetch(register_url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + "userName": userName, + "password": password, + "firstName":firstName, + "lastName":lastName, + "email":email + }), + }); + + const json = await res.json(); + if (json.status) { + // Save username in session and reload home + sessionStorage.setItem('username', json.userName); + window.location.href = window.location.origin; + } + else if (json.error === "Already Registered") { + alert("The user with same username is already registered"); + window.location.href = window.location.origin; + } +}; + + return( +
+
+ SignUp + +
+
+ +
+
+
+ Username + setUserName(e.target.value)}/> +
+
+ First Name + setFirstName(e.target.value)}/> +
+ +
+ Last Name + setlastName(e.target.value)}/> +
+ +
+ Email + setEmail(e.target.value)}/> +
+ +
+ password + setPassword(e.target.value)}/> +
+ +
+
+ +
+
+
+ ) +} + +export default Register; \ No newline at end of file diff --git a/server/frontend/static/Home.html b/server/frontend/static/Home.html index 7086dcb951..31db8f326a 100644 --- a/server/frontend/static/Home.html +++ b/server/frontend/static/Home.html @@ -1,87 +1,84 @@ - - - -
- ... - ...
- + \ No newline at end of file From 153b2319c50c82cb86f1ada27a86584d995e94d4 Mon Sep 17 00:00:00 2001 From: iintii Date: Sun, 20 Jul 2025 10:22:33 -0400 Subject: [PATCH 04/36] m --- server/database/app.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/server/database/app.js b/server/database/app.js index 00f52b2008..bb5d04a8d8 100644 --- a/server/database/app.js +++ b/server/database/app.js @@ -58,12 +58,17 @@ app.get('/fetchReviews/dealer/:id', async (req, res) => { // Express route to fetch all dealerships app.get('/fetchDealers', async (req, res) => { -//Write your code here + try { + const documents = await Dealerships.find(); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch Dealers by a particular state app.get('/fetchDealers/:state', async (req, res) => { -//Write your code here + }); // Express route to fetch dealer by a particular id From a7cea5fa669169fd8d2d5021a9ae2dbafc152e83 Mon Sep 17 00:00:00 2001 From: iintii Date: Sun, 20 Jul 2025 12:07:06 -0400 Subject: [PATCH 05/36] m --- server/djangoapp/admin.py | 6 ++-- server/djangoapp/migrations/0001_initial.py | 35 +++++++++++++++++++ server/djangoapp/migrations/__init__.py | 0 server/djangoapp/models.py | 38 +++++++++++++++++++-- server/djangoapp/populate.py | 38 ++++++++++++++++++++- server/djangoapp/urls.py | 5 +-- server/djangoapp/views.py | 28 ++++++++++----- server/djangoproj/settings.py | 4 +-- 8 files changed, 136 insertions(+), 18 deletions(-) create mode 100644 server/djangoapp/migrations/0001_initial.py create mode 100644 server/djangoapp/migrations/__init__.py diff --git a/server/djangoapp/admin.py b/server/djangoapp/admin.py index 433657fc64..8b53fb60b4 100644 --- a/server/djangoapp/admin.py +++ b/server/djangoapp/admin.py @@ -1,8 +1,10 @@ -# from django.contrib import admin -# from .models import related models +from django.contrib import admin +from .models import CarMake, CarModel # Register your models here. +admin.site.register(CarMake) +admin.site.register(CarModel) # CarModelInline class diff --git a/server/djangoapp/migrations/0001_initial.py b/server/djangoapp/migrations/0001_initial.py new file mode 100644 index 0000000000..8ae76c69ef --- /dev/null +++ b/server/djangoapp/migrations/0001_initial.py @@ -0,0 +1,35 @@ +# Generated by Django 5.2.4 on 2025-07-20 16:03 + +import django.core.validators +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='CarMake', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100)), + ('description', models.TextField()), + ], + ), + migrations.CreateModel( + name='CarModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('dealer_id', models.IntegerField(null=True)), + ('name', models.CharField(max_length=100)), + ('type', models.CharField(choices=[('SEDAN', 'Sedan'), ('SUV', 'SUV'), ('WAGON', 'Wagon'), ('TRUCK', 'Truck'), ('HATCHBACK', 'Hatchback'), ('COUPE', 'Coupe'), ('CONVERTIBLE', 'Convertible'), ('MINIVAN', 'Minivan'), ('PICKUP', 'Pickup')], default='SUV', max_length=15)), + ('year', models.IntegerField(default=2023, validators=[django.core.validators.MaxValueValidator(2023), django.core.validators.MinValueValidator(2015)])), + ('car_make', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='djangoapp.carmake')), + ], + ), + ] diff --git a/server/djangoapp/migrations/__init__.py b/server/djangoapp/migrations/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index eb101a68c8..44fbf0c5ea 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -1,8 +1,8 @@ # Uncomment the following imports before adding the Model code -# from django.db import models -# from django.utils.timezone import now -# from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models +from django.utils.timezone import now +from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. @@ -13,6 +13,13 @@ # - Any other fields you would like to include in car make model # - __str__ method to print a car make object +class CarMake(models.Model): + name = models.CharField(max_length=100) + description = models.TextField() + + def __str__(self): + return self.name + # Create a Car Model model `class CarModel(models.Model):`: # - Many-To-One relationship to Car Make model (One Car Make has many @@ -23,3 +30,28 @@ # - Year (IntegerField) with min value 2015 and max value 2023 # - Any other fields you would like to include in car model # - __str__ method to print a car make object +class CarModel(models.Model): + car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) # Many-to-One relationship + dealer_id = models.IntegerField(null=True) # Refers to a dealer created in Cloudant database + name = models.CharField(max_length=100) + CAR_TYPES = [ + ('SEDAN', 'Sedan'), + ('SUV', 'SUV'), + ('WAGON', 'Wagon'), + ('TRUCK', 'Truck'), + ('HATCHBACK', 'Hatchback'), + ('COUPE', 'Coupe'), + ('CONVERTIBLE', 'Convertible'), + ('MINIVAN', 'Minivan'), + ('PICKUP', 'Pickup'), + # Add more choices as required + ] + type = models.CharField(max_length=15, choices=CAR_TYPES, default='SUV') + year = models.IntegerField(default=2023, + validators=[ + MaxValueValidator(2023), + MinValueValidator(2015) + ]) + + def __str__(self): + return f"{self.car_make.name} - {self.name}" \ No newline at end of file diff --git a/server/djangoapp/populate.py b/server/djangoapp/populate.py index 1927e09e18..09cc361f5e 100644 --- a/server/djangoapp/populate.py +++ b/server/djangoapp/populate.py @@ -1,2 +1,38 @@ +from .models import CarMake, CarModel + def initiate(): - print("Populate not implemented. Add data manually") + car_make_data = [ + {"name":"NISSAN", "description":"Great cars. Japanese technology"}, + {"name":"Mercedes", "description":"Great cars. German technology"}, + {"name":"Audi", "description":"Great cars. German technology"}, + {"name":"Kia", "description":"Great cars. Korean technology"}, + {"name":"Toyota", "description":"Great cars. Japanese technology"}, + ] + + car_make_instances = [] + for data in car_make_data: + car_make_instances.append(CarMake.objects.create(name=data['name'], description=data['description'])) + + + # Create CarModel instances with the corresponding CarMake instances + car_model_data = [ + {"name":"Pathfinder", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"Qashqai", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"XTRAIL", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"A-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"C-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"E-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"A4", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"A5", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"A6", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"Sorrento", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Carnival", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Cerato", "type":"Sedan", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Corolla", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, + {"name":"Camry", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, + {"name":"Kluger", "type":"SUV", "year": 2023, "car_make":car_make_instances[4]}, + # Add more CarModel instances as needed + ] + + for data in car_model_data: + CarModel.objects.create(name=data['name'], car_make=data['car_make'], type=data['type'], year=data['year']) \ No newline at end of file diff --git a/server/djangoapp/urls.py b/server/djangoapp/urls.py index 0edc274f90..4a0b9603de 100644 --- a/server/djangoapp/urls.py +++ b/server/djangoapp/urls.py @@ -1,8 +1,8 @@ # Uncomment the imports before you add the code -# from django.urls import path +from django.urls import path from django.conf.urls.static import static from django.conf import settings -# from . import views +from . import views app_name = 'djangoapp' urlpatterns = [ @@ -14,5 +14,6 @@ # path for dealer reviews view # path for add a review view + path(route='get_cars', view=views.get_cars, name ='getcars'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index b16409f419..d2bada6dc8 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,19 +1,20 @@ # Uncomment the required imports before adding the code -# from django.shortcuts import render -# from django.http import HttpResponseRedirect, HttpResponse -# from django.contrib.auth.models import User -# from django.shortcuts import get_object_or_404, render, redirect -# from django.contrib.auth import logout -# from django.contrib import messages -# from datetime import datetime +from django.shortcuts import render +from django.http import HttpResponseRedirect, HttpResponse +from django.contrib.auth.models import User +from django.shortcuts import get_object_or_404, render, redirect +from django.contrib.auth import logout +from django.contrib import messages +from datetime import datetime from django.http import JsonResponse from django.contrib.auth import login, authenticate import logging import json from django.views.decorators.csrf import csrf_exempt -# from .populate import initiate +from .populate import initiate +from .models import CarMake, CarModel # Get an instance of a logger @@ -63,3 +64,14 @@ def login_user(request): # Create a `add_review` view to submit a review # def add_review(request): # ... + +def get_cars(request): + count = CarMake.objects.filter().count() + print(count) + if(count == 0): + initiate() + car_models = CarModel.objects.select_related('car_make') + cars = [] + for car_model in car_models: + cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name}) + return JsonResponse({"CarModels":cars}) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index d15f94af5b..2ccbc777b5 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -28,8 +28,8 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS=['localhost','https://brody8991-8000.theianext-0-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai/'] -CSRF_TRUSTED_ORIGINS=['https://brody8991-8000.theianext-0-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai/'] +ALLOWED_HOSTS = ['localhost', 'brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai'] +CSRF_TRUSTED_ORIGINS = ['https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [], From 1c28ab62adca0825448d459c227469cfeeb7e658 Mon Sep 17 00:00:00 2001 From: iintii Date: Sun, 20 Jul 2025 14:16:57 -0400 Subject: [PATCH 06/36] m --- server/djangoapp/.env | 3 ++- server/djangoapp/restapis.py | 36 ++++++++++++++++++++++++++++++- server/djangoapp/urls.py | 5 +++++ server/djangoapp/views.py | 41 ++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 2 deletions(-) diff --git a/server/djangoapp/.env b/server/djangoapp/.env index 01822e542a..91791e42bd 100644 --- a/server/djangoapp/.env +++ b/server/djangoapp/.env @@ -1,2 +1,3 @@ backend_url =your backend url -sentiment_analyzer_url=your code engine deployment url +sentiment_analyzer_url=https://sentianalyzer.1y32t94nuhbv.us-south.codeengine.appdomain.cloud/ +backend_url = https://brody8991-3030.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/ \ No newline at end of file diff --git a/server/djangoapp/restapis.py b/server/djangoapp/restapis.py index 90709d9e3b..dab2084d68 100644 --- a/server/djangoapp/restapis.py +++ b/server/djangoapp/restapis.py @@ -1,5 +1,5 @@ # Uncomment the imports below before you add the function code -# import requests +import requests import os from dotenv import load_dotenv @@ -13,10 +13,44 @@ # def get_request(endpoint, **kwargs): # Add code for get requests to back end +def get_request(endpoint, **kwargs): + params = "" + if(kwargs): + for key,value in kwargs.items(): + params=params+key+"="+value+"&" + + request_url = backend_url+endpoint+"?"+params + + print("GET from {} ".format(request_url)) + try: + # Call get method of requests library with URL and parameters + response = requests.get(request_url) + return response.json() + except: + # If any error occurs + print("Network exception occurred") # def analyze_review_sentiments(text): # request_url = sentiment_analyzer_url+"analyze/"+text # Add code for retrieving sentiments +def analyze_review_sentiments(text): + request_url = sentiment_analyzer_url+"analyze/"+text + try: + # Call get method of requests library with URL and parameters + response = requests.get(request_url) + return response.json() + except Exception as err: + print(f"Unexpected {err=}, {type(err)=}") + print("Network exception occurred") + # def post_review(data_dict): +def post_review(data_dict): + request_url = backend_url+"/insert_review" + try: + response = requests.post(request_url,json=data_dict) + print(response.json()) + return response.json() + except: + print("Network exception occurred") # Add code for posting review diff --git a/server/djangoapp/urls.py b/server/djangoapp/urls.py index 4a0b9603de..0fb3b67006 100644 --- a/server/djangoapp/urls.py +++ b/server/djangoapp/urls.py @@ -12,6 +12,11 @@ # path(route='login', view=views.login_user, name='login'), # path for dealer reviews view + path(route='get_dealers', view=views.get_dealerships, name='get_dealers'), + path(route='get_dealers/', view=views.get_dealerships, name='get_dealers_by_state'), + path(route='dealer/', view=views.get_dealer_details, name='dealer_details'), + path(route='reviews/dealer/', view=views.get_dealer_reviews, name='dealer_details'), + path(route='add_review', view=views.add_review, name='add_review'), # path for add a review view path(route='get_cars', view=views.get_cars, name ='getcars'), diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index d2bada6dc8..89cf850fe4 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -15,6 +15,7 @@ from django.views.decorators.csrf import csrf_exempt from .populate import initiate from .models import CarMake, CarModel +from .restapis import get_request, analyze_review_sentiments, post_review # Get an instance of a logger @@ -75,3 +76,43 @@ def get_cars(request): for car_model in car_models: cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name}) return JsonResponse({"CarModels":cars}) +#Update the `get_dealerships` render list of dealerships all by default, particular state if state is passed +def get_dealerships(request, state="All"): + if(state == "All"): + endpoint = "/fetchDealers" + else: + endpoint = "/fetchDealers/"+state + dealerships = get_request(endpoint) + return JsonResponse({"status":200,"dealers":dealerships}) + +def get_dealer_details(request, dealer_id): + if(dealer_id): + endpoint = "/fetchDealer/"+str(dealer_id) + dealership = get_request(endpoint) + return JsonResponse({"status":200,"dealer":dealership}) + else: + return JsonResponse({"status":400,"message":"Bad Request"}) + +def get_dealer_reviews(request, dealer_id): + # if dealer id has been provided + if(dealer_id): + endpoint = "/fetchReviews/dealer/"+str(dealer_id) + reviews = get_request(endpoint) + for review_detail in reviews: + response = analyze_review_sentiments(review_detail['review']) + print(response) + review_detail['sentiment'] = response['sentiment'] + return JsonResponse({"status":200,"reviews":reviews}) + else: + return JsonResponse({"status":400,"message":"Bad Request"}) + +def add_review(request): + if(request.user.is_anonymous == False): + data = json.loads(request.body) + try: + response = post_review(data) + return JsonResponse({"status":200}) + except: + return JsonResponse({"status":401,"message":"Error in posting review"}) + else: + return JsonResponse({"status":403,"message":"Unauthorized"}) \ No newline at end of file From dcbc0e8ee4cbcc3dbeb792f1708416564135a8e7 Mon Sep 17 00:00:00 2001 From: iintii Date: Tue, 22 Jul 2025 19:43:12 -0400 Subject: [PATCH 07/36] m --- server/frontend/src/components/Home/Home.jsx | 60 ++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 server/frontend/src/components/Home/Home.jsx diff --git a/server/frontend/src/components/Home/Home.jsx b/server/frontend/src/components/Home/Home.jsx new file mode 100644 index 0000000000..3bafb7502e --- /dev/null +++ b/server/frontend/src/components/Home/Home.jsx @@ -0,0 +1,60 @@ +// /home/project/xrwvm-fullstack_developer_capstone/server/frontend/src/components/Home/Home.jsx + +import React from 'react'; +import { Link } from 'react-router-dom'; // Assuming you have react-router-dom installed for navigation + +function Home() { + const containerStyle = { + textAlign: 'center', + padding: '50px', + fontFamily: 'Arial, sans-serif', + }; + + const buttonContainerStyle = { + marginTop: '30px', + }; + + const buttonStyle = { + display: 'inline-block', + margin: '10px', + padding: '12px 25px', + fontSize: '18px', + fontWeight: 'bold', + color: '#fff', + backgroundColor: '#007bff', + border: 'none', + borderRadius: '5px', + cursor: 'pointer', + textDecoration: 'none', // For Link components + }; + + const buttonHoverStyle = { + backgroundColor: '#0056b3', // Darker blue on hover + }; + + return ( +
+

Welcome to Best Cars Dealership!

+

Your one-stop solution for finding the best car deals and managing your dealership network.

+ +
+ {/* Login Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + Login + + + {/* Register Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + Register + + + {/* Dealers Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + View Dealerships + +
+
+ ); +} + +export default Home; \ No newline at end of file From f2c59d6be95935d58de7d1441cf467c5a0567e42 Mon Sep 17 00:00:00 2001 From: iintii Date: Tue, 22 Jul 2025 23:31:01 -0400 Subject: [PATCH 08/36] m --- server/frontend/src/App.js | 27 ++- .../src/components/Dealers/Dealers.jsx | 186 ++++++++++-------- server/frontend/src/components/Home/Home.jsx | 2 +- 3 files changed, 133 insertions(+), 82 deletions(-) diff --git a/server/frontend/src/App.js b/server/frontend/src/App.js index 2d4fb633bb..14ed34277d 100644 --- a/server/frontend/src/App.js +++ b/server/frontend/src/App.js @@ -1,12 +1,35 @@ -import LoginPanel from "./components/Login/Login" +// src/App.js + import { Routes, Route } from "react-router-dom"; +// Corrected import for Login/LoginPanel - assuming LoginPanel is what you want to use for /login +import LoginPanel from "./components/Login/Login"; // This imports the default export from Login.js as LoginPanel import Register from "./components/Register/Register"; +import Dealers from './components/Dealers/Dealers'; + +// **** THESE ARE THE MISSING IMPORTS THAT ARE CAUSING THE ESLINT ERRORS **** +// You need to import these components from their respective files. +// Adjust the paths based on where these component files actually live in your project. +// Common assumption: each component has its own folder within `src/components/` +import Home from './components/Home/Home'; // Assuming your Home component is in src/components/Home/Home.js +import Dealer from './components/Dealers/Dealer'; // Assuming your Dealer component is in src/components/Dealer/Dealer.js + // Assuming PostReview is in src/components/PostReview/PostReview.js +import Header from './components/Header/Header'; function App() { return ( + + } /> + {/* If LoginPanel is the component for your login page, use it here: */} } /> - }/> + {/* If you have a separate component named 'Login' that is *not* LoginPanel, + then you would need to import 'Login' as well: import Login from './components/Login/LoginComponent'; + But typically, LoginPanel IS the Login component. + */} + } /> + } /> + } /> + ); } diff --git a/server/frontend/src/components/Dealers/Dealers.jsx b/server/frontend/src/components/Dealers/Dealers.jsx index db3410680c..e4fa7a749a 100644 --- a/server/frontend/src/components/Dealers/Dealers.jsx +++ b/server/frontend/src/components/Dealers/Dealers.jsx @@ -5,92 +5,120 @@ import Header from '../Header/Header'; import review_icon from "../assets/reviewicon.png" const Dealers = () => { - const [dealersList, setDealersList] = useState([]); - // let [state, setState] = useState("") - let [states, setStates] = useState([]) + const [dealersList, setDealersList] = useState([]); + const [states, setStates] = useState([]); + const [selectedState, setSelectedState] = useState('All'); // New state to manage the selected filter value - // let root_url = window.location.origin - let dealer_url ="/djangoapp/get_dealers"; - - let dealer_url_by_state = "/djangoapp/get_dealers/"; - - const filterDealers = async (state) => { - dealer_url_by_state = dealer_url_by_state+state; - const res = await fetch(dealer_url_by_state, { - method: "GET" - }); - const retobj = await res.json(); - if(retobj.status === 200) { - let state_dealers = Array.from(retobj.dealers) - setDealersList(state_dealers) - } - } + // Function to fetch dealerships based on the selected state + const fetchDealerships = async (stateParam) => { // Renamed parameter to avoid conflict with useState + let url = `/djangoapp/get_dealers`; + if (stateParam && stateParam !== 'All') { + url = `/djangoapp/get_dealers/${stateParam}`; // Correctly form URL for specific state + } + + try { + const res = await fetch(url, { + method: "GET" + }); + const retobj = await res.json(); + if (retobj.status === 200) { + setDealersList(Array.from(retobj.dealers)); + } else { + console.error("Failed to fetch dealerships:", retobj.message); + setDealersList([]); // Clear list on error + } + } catch (error) { + console.error("Network error fetching dealerships:", error); + setDealersList([]); // Clear list on network error + } + }; - const get_dealers = async ()=>{ - const res = await fetch(dealer_url, { - method: "GET" - }); - const retobj = await res.json(); - if(retobj.status === 200) { - let all_dealers = Array.from(retobj.dealers) - let states = []; - all_dealers.forEach((dealer)=>{ - states.push(dealer.state) + // Function to get all dealers and populate states dropdown initially + const get_all_dealers_and_states = async () => { + const res = await fetch("/djangoapp/get_dealers", { // Always fetch all initially to get states + method: "GET" }); + const retobj = await res.json(); + if (retobj.status === 200) { + let all_dealers = Array.from(retobj.dealers); + let uniqueStates = new Set(); + all_dealers.forEach((dealer) => { + uniqueStates.add(dealer.state); + }); + setStates(Array.from(uniqueStates)); // Set unique states for the dropdown + setDealersList(all_dealers); // Set the initial list of all dealers + } else { + console.error("Failed to fetch initial dealerships and states:", retobj.message); + } + }; - setStates(Array.from(new Set(states))) - setDealersList(all_dealers) - } - } - useEffect(() => { - get_dealers(); - },[]); + // Use useEffect to fetch initial data and then re-fetch when selectedState changes + useEffect(() => { + // On initial mount, get all dealers and populate states + get_all_dealers_and_states(); + }, []); // Empty dependency array: runs only once on component mount + // This useEffect watches for changes in selectedState and fetches dealers accordingly + useEffect(() => { + if (selectedState) { // Ensure selectedState is not null/undefined + fetchDealerships(selectedState); + } + }, [selectedState]); // Dependency array: re-run when selectedState changes -let isLoggedIn = sessionStorage.getItem("username") != null ? true : false; -return( -
-
+ const handleStateChange = (e) => { + setSelectedState(e.target.value); // Update the selectedState + }; - - - - - - - - - {isLoggedIn ? ( - - ):<> - } - - {dealersList.map(dealer => ( - - - - - - - - {isLoggedIn ? ( - - ):<> - } - - ))} -
IDDealer NameCityAddressZip - + let isLoggedIn = sessionStorage.getItem("username") != null ? true : false; +return ( +
+
-
Review Dealer
{dealer['id']}{dealer['full_name']}{dealer['city']}{dealer['address']}{dealer['zip']}{dealer['state']}Post Review
; -
-) + + + + + + + + + + {isLoggedIn ? ( + + ) : <> + } + + + + {dealersList.length === 0 ? ( + + ) : ( + dealersList.map(dealer => ( + {/* Add key for list items */} + + + + + + + {isLoggedIn ? ( + + ) : <> + } + + )) + )} + +
IDDealer NameCityAddressZip + + Review Dealer
Loading dealerships...
{dealer['id']}{dealer['full_name']}{dealer['city']}{dealer['address']}{dealer['zip']}{dealer['state']}Post Review
+ + ); } -export default Dealers +export default Dealers; \ No newline at end of file diff --git a/server/frontend/src/components/Home/Home.jsx b/server/frontend/src/components/Home/Home.jsx index 3bafb7502e..35c3e4aac8 100644 --- a/server/frontend/src/components/Home/Home.jsx +++ b/server/frontend/src/components/Home/Home.jsx @@ -49,7 +49,7 @@ function Home() { {/* Dealers Button */} - e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> View Dealerships From 6e08a987f2667ad3c700d5ea7ed46712a652cd79 Mon Sep 17 00:00:00 2001 From: iintii Date: Tue, 22 Jul 2025 23:43:02 -0400 Subject: [PATCH 09/36] m --- server/frontend/src/App.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/frontend/src/App.js b/server/frontend/src/App.js index 14ed34277d..631f265741 100644 --- a/server/frontend/src/App.js +++ b/server/frontend/src/App.js @@ -14,6 +14,7 @@ import Home from './components/Home/Home'; // Assuming your Home component is in import Dealer from './components/Dealers/Dealer'; // Assuming your Dealer component is in src/components/Dealer/Dealer.js // Assuming PostReview is in src/components/PostReview/PostReview.js import Header from './components/Header/Header'; +import PostReview from "./components/Dealers/PostReview" function App() { return ( @@ -29,6 +30,7 @@ function App() { } /> } /> } /> + } /> ); From d779e608c17105c16288130a27d48b8a0c73a6d2 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 10:00:08 -0400 Subject: [PATCH 10/36] Create main.yml --- .github/workflows/main.yml | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000000..1d5c207add --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,59 @@ +name: 'Lint Code' + +on: + push: + branches: [master, main] + pull_request: + branches: [master, main] + +jobs: + lint_python: + name: Lint Python Files + runs-on: ubuntu-latest + + steps: + + - name: Checkout Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.12 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 + + - name: Print working directory + run: pwd + + - name: Run Linter + run: | + pwd + # This command finds all Python files recursively and runs flake8 on them + find . -name "*.py" -exec flake8 {} + + echo "Linted all the python files successfully" + + lint_js: + name: Lint JavaScript Files + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@v3 + + - name: Install Node.js + uses: actions/setup-node@v3 + with: + node-version: 14 + + - name: Install JSHint + run: npm install jshint --global + + - name: Run Linter + run: | + # This command finds all JavaScript files recursively and runs JSHint on them + find ./server/database -name "*.js" -exec jshint {} + + echo "Linted all the js files successfully" From 6d712998f492135547d262d46e0e7aa12cddcf7a Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 10:04:46 -0400 Subject: [PATCH 11/36] Update urls.py --- server/djangoproj/urls.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/djangoproj/urls.py b/server/djangoproj/urls.py index e97a26491a..af93a653bc 100644 --- a/server/djangoproj/urls.py +++ b/server/djangoproj/urls.py @@ -20,7 +20,7 @@ from django.conf import settings urlpatterns = [ - path('contact/', TemplateView.as_view(template_name="Contact.html")), + path('contact/', TemplateView.as_view(template_name="Contact.html")), path('about/', TemplateView.as_view(template_name="About.html")), path('admin/', admin.site.urls), path('djangoapp/', include('djangoapp.urls')), From 7c10ebe59051614179a406ef65e3c36399e292dd Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 10:19:43 -0400 Subject: [PATCH 12/36] Update main.yml --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1d5c207add..5ba85aabb0 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,5 +55,5 @@ jobs: - name: Run Linter run: | # This command finds all JavaScript files recursively and runs JSHint on them - find ./server/database -name "*.js" -exec jshint {} + + find ./server/database -name "*.js" -exec jshint --esversion=6 {} + echo "Linted all the js files successfully" From 46a496d405f2eabf0767355df5ff6e804d031ac9 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:44:00 -0400 Subject: [PATCH 13/36] Update main.yml --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5ba85aabb0..1d5c207add 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,5 +55,5 @@ jobs: - name: Run Linter run: | # This command finds all JavaScript files recursively and runs JSHint on them - find ./server/database -name "*.js" -exec jshint --esversion=6 {} + + find ./server/database -name "*.js" -exec jshint {} + echo "Linted all the js files successfully" From 752c6524f2dc86942deb58fc0b750dcc280e5da2 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:47:39 -0400 Subject: [PATCH 14/36] Update main.yml --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1d5c207add..5ba85aabb0 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,5 +55,5 @@ jobs: - name: Run Linter run: | # This command finds all JavaScript files recursively and runs JSHint on them - find ./server/database -name "*.js" -exec jshint {} + + find ./server/database -name "*.js" -exec jshint --esversion=6 {} + echo "Linted all the js files successfully" From 6a8bb30a9e4ea683ec2314fe753605970bc97447 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:56:21 -0400 Subject: [PATCH 15/36] Update main.yml From 3b5d87c916df7cbeb74a1f7d2a805f78a0725d9f Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:57:57 -0400 Subject: [PATCH 16/36] Create .jshintrc --- .jshintrc | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .jshintrc diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000000..2b6f469f0c --- /dev/null +++ b/.jshintrc @@ -0,0 +1,3 @@ +{ + "esversion": 6 +} From 51c9c7676078ea6dd785429ba86bd2525740cefe Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:58:31 -0400 Subject: [PATCH 17/36] Update main.yml --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5ba85aabb0..1d5c207add 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,5 +55,5 @@ jobs: - name: Run Linter run: | # This command finds all JavaScript files recursively and runs JSHint on them - find ./server/database -name "*.js" -exec jshint --esversion=6 {} + + find ./server/database -name "*.js" -exec jshint {} + echo "Linted all the js files successfully" From 56b119ca0fece18eafbb9104ce921d3ff0c29227 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 15:07:53 -0400 Subject: [PATCH 18/36] Update app.js --- server/database/app.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/server/database/app.js b/server/database/app.js index bb5d04a8d8..ff9f50b982 100644 --- a/server/database/app.js +++ b/server/database/app.js @@ -83,16 +83,16 @@ app.post('/insert_review', express.raw({ type: '*/*' }), async (req, res) => { let new_id = documents[0]['id']+1 const review = new Reviews({ - "id": new_id, - "name": data['name'], - "dealership": data['dealership'], - "review": data['review'], - "purchase": data['purchase'], - "purchase_date": data['purchase_date'], - "car_make": data['car_make'], - "car_model": data['car_model'], - "car_year": data['car_year'], - }); + "id": new_id, + "name": data.name, + "dealership": data.dealership, + "review": data.review, + "purchase": data.purchase, + "purchase_date": data.purchase_date, + "car_make": data.car_make, + "car_model": data.car_model, // <-- Changed + "car_year": data.car_year // <-- Changed +}); try { const savedReview = await review.save(); From 33316e1b82e9a133246d76164499a5dc4d1c1909 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 15:13:07 -0400 Subject: [PATCH 19/36] Update settings.py --- server/djangoproj/settings.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index 2ccbc777b5..d3e0ebceb3 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -22,7 +22,7 @@ # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY =\ +SECRET_KEY = \ 'django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0' # SECURITY WARNING: don't run with debug turned on in production! @@ -61,7 +61,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR,'frontend/static')], + 'DIRS': [os.path.join(BASE_DIR, 'frontend/static')], # Fix Line 64: E231 missing whitespace after ',' 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -89,8 +89,9 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': - 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + 'NAME': ( # Fix Line 93: E501 line too long (83 > 79 characters) + 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' + ), }, { 'NAME': @@ -135,6 +136,6 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [ - os.path.join(BASE_DIR,'frontend/static') + os.path.join(BASE_DIR, 'frontend/static') # Fix Line 138: E231 missing whitespace after ',' ] - +# Fix Line 140: W391 blank line at end of file (removed the blank line) From 0ba605b219bbb497f52d59df0fbdfb0ed4fd26f7 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 15:14:49 -0400 Subject: [PATCH 20/36] Update settings.py --- server/djangoproj/settings.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index d3e0ebceb3..82959be702 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -25,7 +25,7 @@ SECRET_KEY = \ 'django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0' -# SECURITY WARNING: don't run with debug turned on in production! +# SECURITY WARNING: don't run with debug on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', 'brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai'] @@ -61,7 +61,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, 'frontend/static')], # Fix Line 64: E231 missing whitespace after ',' + 'DIRS': [os.path.join(BASE_DIR, 'frontend/static')], # Corrected spacing 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -89,9 +89,9 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': ( # Fix Line 93: E501 line too long (83 > 79 characters) + 'NAME': ( 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' - ), + ), # User similarity validator }, { 'NAME': @@ -136,6 +136,5 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [ - os.path.join(BASE_DIR, 'frontend/static') # Fix Line 138: E231 missing whitespace after ',' + os.path.join(BASE_DIR, 'frontend/static') # Static files directory ] -# Fix Line 140: W391 blank line at end of file (removed the blank line) From b3b677673b07f31bf804d7306005bf5c3074b59a Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 15:17:10 -0400 Subject: [PATCH 21/36] Update settings.py --- server/djangoproj/settings.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index 82959be702..79705d8531 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -28,8 +28,13 @@ # SECURITY WARNING: don't run with debug on in production! DEBUG = True -ALLOWED_HOSTS = ['localhost', 'brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai'] -CSRF_TRUSTED_ORIGINS = ['https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai'] +ALLOWED_HOSTS = [ # Fix Line 31: E501 line too long + 'localhost', + 'brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai' +] +CSRF_TRUSTED_ORIGINS = [ # Fix Line 32: E501 line too long + 'https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai' +] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [], @@ -61,7 +66,9 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, 'frontend/static')], # Corrected spacing + 'DIRS': [ # Fix Line 64: E501 line too long + os.path.join(BASE_DIR, 'frontend/static') + ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -89,7 +96,7 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': ( + 'NAME': ( # Fix Line 93: E501 line too long (using parentheses) 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' ), # User similarity validator }, From 85f0530221d0bff40386a4c06b0da7e913d583bd Mon Sep 17 00:00:00 2001 From: iintii Date: Wed, 23 Jul 2025 19:31:09 -0400 Subject: [PATCH 22/36] formatted --- server/djangoapp/apps.py | 2 +- server/djangoapp/microservices/app.py | 15 +-- server/djangoapp/migrations/0001_initial.py | 73 ++++++++++--- server/djangoapp/models.py | 41 +++---- server/djangoapp/populate.py | 113 ++++++++++++++++---- server/djangoapp/restapis.py | 27 +++-- server/djangoapp/urls.py | 30 ++++-- server/djangoapp/views.py | 54 ++++++---- server/djangoproj/asgi.py | 2 +- server/djangoproj/settings.py | 98 ++++++++--------- server/djangoproj/urls.py | 11 +- server/djangoproj/wsgi.py | 2 +- server/manage.py | 4 +- 13 files changed, 303 insertions(+), 169 deletions(-) diff --git a/server/djangoapp/apps.py b/server/djangoapp/apps.py index 3800cc769c..ff2365a747 100644 --- a/server/djangoapp/apps.py +++ b/server/djangoapp/apps.py @@ -2,4 +2,4 @@ class DjangoappConfig(AppConfig): - name = 'djangoapp' + name = "djangoapp" diff --git a/server/djangoapp/microservices/app.py b/server/djangoapp/microservices/app.py index 9d967e6fd9..03fa076444 100644 --- a/server/djangoapp/microservices/app.py +++ b/server/djangoapp/microservices/app.py @@ -1,30 +1,31 @@ from flask import Flask from nltk.sentiment import SentimentIntensityAnalyzer import json + app = Flask("Sentiment Analyzer") sia = SentimentIntensityAnalyzer() -@app.get('/') +@app.get("/") def home(): return "Welcome to the Sentiment Analyzer. \ Use /analyze/text to get the sentiment" -@app.get('/analyze/') +@app.get("/analyze/") def analyze_sentiment(input_txt): scores = sia.polarity_scores(input_txt) print(scores) - pos = float(scores['pos']) - neg = float(scores['neg']) - neu = float(scores['neu']) + pos = float(scores["pos"]) + neg = float(scores["neg"]) + neu = float(scores["neu"]) res = "positive" print("pos neg nue ", pos, neg, neu) - if (neg > pos and neg > neu): + if neg > pos and neg > neu: res = "negative" - elif (neu > neg and neu > pos): + elif neu > neg and neu > pos: res = "neutral" res = json.dumps({"sentiment": res}) print(res) diff --git a/server/djangoapp/migrations/0001_initial.py b/server/djangoapp/migrations/0001_initial.py index 8ae76c69ef..f560c49aa0 100644 --- a/server/djangoapp/migrations/0001_initial.py +++ b/server/djangoapp/migrations/0001_initial.py @@ -9,27 +9,74 @@ class Migration(migrations.Migration): initial = True - dependencies = [ - ] + dependencies = [] operations = [ migrations.CreateModel( - name='CarMake', + name="CarMake", fields=[ - ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=100)), - ('description', models.TextField()), + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=100)), + ("description", models.TextField()), ], ), migrations.CreateModel( - name='CarModel', + name="CarModel", fields=[ - ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('dealer_id', models.IntegerField(null=True)), - ('name', models.CharField(max_length=100)), - ('type', models.CharField(choices=[('SEDAN', 'Sedan'), ('SUV', 'SUV'), ('WAGON', 'Wagon'), ('TRUCK', 'Truck'), ('HATCHBACK', 'Hatchback'), ('COUPE', 'Coupe'), ('CONVERTIBLE', 'Convertible'), ('MINIVAN', 'Minivan'), ('PICKUP', 'Pickup')], default='SUV', max_length=15)), - ('year', models.IntegerField(default=2023, validators=[django.core.validators.MaxValueValidator(2023), django.core.validators.MinValueValidator(2015)])), - ('car_make', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='djangoapp.carmake')), + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("dealer_id", models.IntegerField(null=True)), + ("name", models.CharField(max_length=100)), + ( + "type", + models.CharField( + choices=[ + ("SEDAN", "Sedan"), + ("SUV", "SUV"), + ("WAGON", "Wagon"), + ("TRUCK", "Truck"), + ("HATCHBACK", "Hatchback"), + ("COUPE", "Coupe"), + ("CONVERTIBLE", "Convertible"), + ("MINIVAN", "Minivan"), + ("PICKUP", "Pickup"), + ], + default="SUV", + max_length=15, + ), + ), + ( + "year", + models.IntegerField( + default=2023, + validators=[ + django.core.validators.MaxValueValidator(2023), + django.core.validators.MinValueValidator(2015), + ], + ), + ), + ( + "car_make", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="djangoapp.carmake", + ), + ), ], ), ] diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index 44fbf0c5ea..f93efbc169 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -13,12 +13,13 @@ # - Any other fields you would like to include in car make model # - __str__ method to print a car make object + class CarMake(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): - return self.name + return self.name # Create a Car Model model `class CarModel(models.Model):`: @@ -31,27 +32,29 @@ def __str__(self): # - Any other fields you would like to include in car model # - __str__ method to print a car make object class CarModel(models.Model): - car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) # Many-to-One relationship - dealer_id = models.IntegerField(null=True) # Refers to a dealer created in Cloudant database + car_make = models.ForeignKey( + CarMake, on_delete=models.CASCADE + ) # Many-to-One relationship + dealer_id = models.IntegerField( + null=True + ) # Refers to a dealer created in Cloudant database name = models.CharField(max_length=100) CAR_TYPES = [ - ('SEDAN', 'Sedan'), - ('SUV', 'SUV'), - ('WAGON', 'Wagon'), - ('TRUCK', 'Truck'), - ('HATCHBACK', 'Hatchback'), - ('COUPE', 'Coupe'), - ('CONVERTIBLE', 'Convertible'), - ('MINIVAN', 'Minivan'), - ('PICKUP', 'Pickup'), + ("SEDAN", "Sedan"), + ("SUV", "SUV"), + ("WAGON", "Wagon"), + ("TRUCK", "Truck"), + ("HATCHBACK", "Hatchback"), + ("COUPE", "Coupe"), + ("CONVERTIBLE", "Convertible"), + ("MINIVAN", "Minivan"), + ("PICKUP", "Pickup"), # Add more choices as required ] - type = models.CharField(max_length=15, choices=CAR_TYPES, default='SUV') - year = models.IntegerField(default=2023, - validators=[ - MaxValueValidator(2023), - MinValueValidator(2015) - ]) + type = models.CharField(max_length=15, choices=CAR_TYPES, default="SUV") + year = models.IntegerField( + default=2023, validators=[MaxValueValidator(2023), MinValueValidator(2015)] + ) def __str__(self): - return f"{self.car_make.name} - {self.name}" \ No newline at end of file + return f"{self.car_make.name} - {self.name}" diff --git a/server/djangoapp/populate.py b/server/djangoapp/populate.py index 09cc361f5e..1df6368751 100644 --- a/server/djangoapp/populate.py +++ b/server/djangoapp/populate.py @@ -1,38 +1,105 @@ from .models import CarMake, CarModel + def initiate(): car_make_data = [ - {"name":"NISSAN", "description":"Great cars. Japanese technology"}, - {"name":"Mercedes", "description":"Great cars. German technology"}, - {"name":"Audi", "description":"Great cars. German technology"}, - {"name":"Kia", "description":"Great cars. Korean technology"}, - {"name":"Toyota", "description":"Great cars. Japanese technology"}, + {"name": "NISSAN", "description": "Great cars. Japanese technology"}, + {"name": "Mercedes", "description": "Great cars. German technology"}, + {"name": "Audi", "description": "Great cars. German technology"}, + {"name": "Kia", "description": "Great cars. Korean technology"}, + {"name": "Toyota", "description": "Great cars. Japanese technology"}, ] car_make_instances = [] for data in car_make_data: - car_make_instances.append(CarMake.objects.create(name=data['name'], description=data['description'])) - + car_make_instances.append( + CarMake.objects.create(name=data["name"], description=data["description"]) + ) # Create CarModel instances with the corresponding CarMake instances car_model_data = [ - {"name":"Pathfinder", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, - {"name":"Qashqai", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, - {"name":"XTRAIL", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, - {"name":"A-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, - {"name":"C-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, - {"name":"E-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, - {"name":"A4", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, - {"name":"A5", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, - {"name":"A6", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, - {"name":"Sorrento", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, - {"name":"Carnival", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, - {"name":"Cerato", "type":"Sedan", "year": 2023, "car_make":car_make_instances[3]}, - {"name":"Corolla", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, - {"name":"Camry", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, - {"name":"Kluger", "type":"SUV", "year": 2023, "car_make":car_make_instances[4]}, + { + "name": "Pathfinder", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "Qashqai", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "XTRAIL", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "A-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + { + "name": "C-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + { + "name": "E-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + {"name": "A4", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, + {"name": "A5", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, + {"name": "A6", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, + { + "name": "Sorrento", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Carnival", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Cerato", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Corolla", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[4], + }, + { + "name": "Camry", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[4], + }, + { + "name": "Kluger", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[4], + }, # Add more CarModel instances as needed ] for data in car_model_data: - CarModel.objects.create(name=data['name'], car_make=data['car_make'], type=data['type'], year=data['year']) \ No newline at end of file + CarModel.objects.create( + name=data["name"], + car_make=data["car_make"], + type=data["type"], + year=data["year"], + ) diff --git a/server/djangoapp/restapis.py b/server/djangoapp/restapis.py index dab2084d68..6f890eb19a 100644 --- a/server/djangoapp/restapis.py +++ b/server/djangoapp/restapis.py @@ -5,21 +5,21 @@ load_dotenv() -backend_url = os.getenv( - 'backend_url', default="http://localhost:3030") +backend_url = os.getenv("backend_url", default="http://localhost:3030") sentiment_analyzer_url = os.getenv( - 'sentiment_analyzer_url', - default="http://localhost:5050/") + "sentiment_analyzer_url", default="http://localhost:5050/" +) + # def get_request(endpoint, **kwargs): # Add code for get requests to back end def get_request(endpoint, **kwargs): params = "" - if(kwargs): - for key,value in kwargs.items(): - params=params+key+"="+value+"&" + if kwargs: + for key, value in kwargs.items(): + params = params + key + "=" + value + "&" - request_url = backend_url+endpoint+"?"+params + request_url = backend_url + endpoint + "?" + params print("GET from {} ".format(request_url)) try: @@ -30,12 +30,14 @@ def get_request(endpoint, **kwargs): # If any error occurs print("Network exception occurred") + # def analyze_review_sentiments(text): # request_url = sentiment_analyzer_url+"analyze/"+text # Add code for retrieving sentiments + def analyze_review_sentiments(text): - request_url = sentiment_analyzer_url+"analyze/"+text + request_url = sentiment_analyzer_url + "analyze/" + text try: # Call get method of requests library with URL and parameters response = requests.get(request_url) @@ -44,13 +46,16 @@ def analyze_review_sentiments(text): print(f"Unexpected {err=}, {type(err)=}") print("Network exception occurred") + # def post_review(data_dict): def post_review(data_dict): - request_url = backend_url+"/insert_review" + request_url = backend_url + "/insert_review" try: - response = requests.post(request_url,json=data_dict) + response = requests.post(request_url, json=data_dict) print(response.json()) return response.json() except: print("Network exception occurred") + + # Add code for posting review diff --git a/server/djangoapp/urls.py b/server/djangoapp/urls.py index 0fb3b67006..ea4140b4d0 100644 --- a/server/djangoapp/urls.py +++ b/server/djangoapp/urls.py @@ -4,21 +4,29 @@ from django.conf import settings from . import views -app_name = 'djangoapp' +app_name = "djangoapp" urlpatterns = [ # # path for registration - # path for login # path(route='login', view=views.login_user, name='login'), - # path for dealer reviews view - path(route='get_dealers', view=views.get_dealerships, name='get_dealers'), - path(route='get_dealers/', view=views.get_dealerships, name='get_dealers_by_state'), - path(route='dealer/', view=views.get_dealer_details, name='dealer_details'), - path(route='reviews/dealer/', view=views.get_dealer_reviews, name='dealer_details'), - path(route='add_review', view=views.add_review, name='add_review'), - + path(route="get_dealers", view=views.get_dealerships, name="get_dealers"), + path( + route="get_dealers/", + view=views.get_dealerships, + name="get_dealers_by_state", + ), + path( + route="dealer/", + view=views.get_dealer_details, + name="dealer_details", + ), + path( + route="reviews/dealer/", + view=views.get_dealer_reviews, + name="dealer_details", + ), + path(route="add_review", view=views.add_review, name="add_review"), # path for add a review view - path(route='get_cars', view=views.get_cars, name ='getcars'), - + path(route="get_cars", view=views.get_cars, name="getcars"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index 89cf850fe4..bbe17d5ca6 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -24,13 +24,14 @@ # Create your views here. + # Create a `login_request` view to handle sign in request @csrf_exempt def login_user(request): # Get username and password from request.POST dictionary data = json.loads(request.body) - username = data['userName'] - password = data['password'] + username = data["userName"] + password = data["password"] # Try to check if provide credential can be authenticated user = authenticate(username=username, password=password) data = {"userName": username} @@ -40,6 +41,7 @@ def login_user(request): data = {"userName": username, "status": "Authenticated"} return JsonResponse(data) + # Create a `logout_request` view to handle sign out request # def logout_request(request): # ... @@ -66,53 +68,59 @@ def login_user(request): # def add_review(request): # ... + def get_cars(request): count = CarMake.objects.filter().count() print(count) - if(count == 0): + if count == 0: initiate() - car_models = CarModel.objects.select_related('car_make') + car_models = CarModel.objects.select_related("car_make") cars = [] for car_model in car_models: cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name}) - return JsonResponse({"CarModels":cars}) -#Update the `get_dealerships` render list of dealerships all by default, particular state if state is passed + return JsonResponse({"CarModels": cars}) + + +# Update the `get_dealerships` render list of dealerships all by default, particular state if state is passed def get_dealerships(request, state="All"): - if(state == "All"): + if state == "All": endpoint = "/fetchDealers" else: - endpoint = "/fetchDealers/"+state + endpoint = "/fetchDealers/" + state dealerships = get_request(endpoint) - return JsonResponse({"status":200,"dealers":dealerships}) + return JsonResponse({"status": 200, "dealers": dealerships}) + def get_dealer_details(request, dealer_id): - if(dealer_id): - endpoint = "/fetchDealer/"+str(dealer_id) + if dealer_id: + endpoint = "/fetchDealer/" + str(dealer_id) dealership = get_request(endpoint) - return JsonResponse({"status":200,"dealer":dealership}) + return JsonResponse({"status": 200, "dealer": dealership}) else: - return JsonResponse({"status":400,"message":"Bad Request"}) + return JsonResponse({"status": 400, "message": "Bad Request"}) + def get_dealer_reviews(request, dealer_id): # if dealer id has been provided - if(dealer_id): - endpoint = "/fetchReviews/dealer/"+str(dealer_id) + if dealer_id: + endpoint = "/fetchReviews/dealer/" + str(dealer_id) reviews = get_request(endpoint) for review_detail in reviews: - response = analyze_review_sentiments(review_detail['review']) + response = analyze_review_sentiments(review_detail["review"]) print(response) - review_detail['sentiment'] = response['sentiment'] - return JsonResponse({"status":200,"reviews":reviews}) + review_detail["sentiment"] = response["sentiment"] + return JsonResponse({"status": 200, "reviews": reviews}) else: - return JsonResponse({"status":400,"message":"Bad Request"}) + return JsonResponse({"status": 400, "message": "Bad Request"}) + def add_review(request): - if(request.user.is_anonymous == False): + if request.user.is_anonymous == False: data = json.loads(request.body) try: response = post_review(data) - return JsonResponse({"status":200}) + return JsonResponse({"status": 200}) except: - return JsonResponse({"status":401,"message":"Error in posting review"}) + return JsonResponse({"status": 401, "message": "Error in posting review"}) else: - return JsonResponse({"status":403,"message":"Unauthorized"}) \ No newline at end of file + return JsonResponse({"status": 403, "message": "Unauthorized"}) diff --git a/server/djangoproj/asgi.py b/server/djangoproj/asgi.py index c9336c553c..91b3a676de 100644 --- a/server/djangoproj/asgi.py +++ b/server/djangoproj/asgi.py @@ -11,6 +11,6 @@ from django.core.asgi import get_asgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") application = get_asgi_application() diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index 79705d8531..d8d4ae47d1 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -22,95 +22,91 @@ # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = \ - 'django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0' +SECRET_KEY = "django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0" # SECURITY WARNING: don't run with debug on in production! DEBUG = True ALLOWED_HOSTS = [ # Fix Line 31: E501 line too long - 'localhost', - 'brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai' + "localhost", + "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai", ] CSRF_TRUSTED_ORIGINS = [ # Fix Line 32: E501 line too long - 'https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai' + "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai" ] REST_FRAMEWORK = { - 'DEFAULT_AUTHENTICATION_CLASSES': [], + "DEFAULT_AUTHENTICATION_CLASSES": [], } # Application definition INSTALLED_APPS = [ - 'djangoapp.apps.DjangoappConfig', - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', + "djangoapp.apps.DjangoappConfig", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", ] MIDDLEWARE = [ - 'django.middleware.security.SecurityMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", ] -ROOT_URLCONF = 'djangoproj.urls' +ROOT_URLCONF = "djangoproj.urls" TEMPLATES = [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [ # Fix Line 64: E501 line too long - os.path.join(BASE_DIR, 'frontend/static') + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [ # Fix Line 64: E501 line too long + os.path.join(BASE_DIR, "frontend/static") ], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], }, }, ] -WSGI_APPLICATION = 'djangoproj.wsgi.application' +WSGI_APPLICATION = "djangoproj.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': ( # Fix Line 93: E501 line too long (using parentheses) - 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' + "NAME": ( # Fix Line 93: E501 line too long (using parentheses) + "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" ), # User similarity validator }, { - 'NAME': - 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { - 'NAME': - 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { - 'NAME': - 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -118,9 +114,9 @@ # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = "en-us" -TIME_ZONE = 'UTC' +TIME_ZONE = "UTC" USE_I18N = True @@ -132,16 +128,14 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ -STATIC_URL = '/static/' -STATIC_ROOT = os.path.join(BASE_DIR, 'static') -MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') -MEDIA_URL = '/media/' +STATIC_URL = "/static/" +STATIC_ROOT = os.path.join(BASE_DIR, "static") +MEDIA_ROOT = os.path.join(STATIC_ROOT, "media") +MEDIA_URL = "/media/" # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -STATICFILES_DIRS = [ - os.path.join(BASE_DIR, 'frontend/static') # Static files directory -] +STATICFILES_DIRS = [os.path.join(BASE_DIR, "frontend/static")] # Static files directory diff --git a/server/djangoproj/urls.py b/server/djangoproj/urls.py index af93a653bc..8d07a685a3 100644 --- a/server/djangoproj/urls.py +++ b/server/djangoproj/urls.py @@ -13,6 +13,7 @@ 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.views.generic import TemplateView @@ -20,9 +21,9 @@ from django.conf import settings urlpatterns = [ - path('contact/', TemplateView.as_view(template_name="Contact.html")), - path('about/', TemplateView.as_view(template_name="About.html")), - path('admin/', admin.site.urls), - path('djangoapp/', include('djangoapp.urls')), - path('', TemplateView.as_view(template_name="Home.html")), + path("contact/", TemplateView.as_view(template_name="Contact.html")), + path("about/", TemplateView.as_view(template_name="About.html")), + path("admin/", admin.site.urls), + path("djangoapp/", include("djangoapp.urls")), + path("", TemplateView.as_view(template_name="Home.html")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/server/djangoproj/wsgi.py b/server/djangoproj/wsgi.py index 171ab807e3..b0c3e2a268 100644 --- a/server/djangoproj/wsgi.py +++ b/server/djangoproj/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") application = get_wsgi_application() diff --git a/server/manage.py b/server/manage.py index af7e44b832..4d9551ce86 100755 --- a/server/manage.py +++ b/server/manage.py @@ -6,7 +6,7 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: @@ -18,5 +18,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main() From 1bcec65487369125ec0d16ddea440d556996ebc4 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 20:03:02 -0400 Subject: [PATCH 23/36] Update main.yml From c4cba1bf1e502b70f0f40c5e4293210b6fef13e0 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 20:11:01 -0400 Subject: [PATCH 24/36] Update settings.py --- server/djangoproj/settings.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index d8d4ae47d1..fa2dc09a42 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -27,11 +27,11 @@ # SECURITY WARNING: don't run with debug on in production! DEBUG = True -ALLOWED_HOSTS = [ # Fix Line 31: E501 line too long +ALLOWED_HOSTS = [ # Fix Line 31 (originally 31 in the current context) "localhost", "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai", ] -CSRF_TRUSTED_ORIGINS = [ # Fix Line 32: E501 line too long +CSRF_TRUSTED_ORIGINS = [ # Fix Line 32 (originally 32 in the current context) "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai" ] @@ -65,7 +65,7 @@ TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", - "DIRS": [ # Fix Line 64: E501 line too long + "DIRS": [ # Fix Line 64 (originally 64 in the current context) os.path.join(BASE_DIR, "frontend/static") ], "APP_DIRS": True, @@ -93,20 +93,25 @@ } } -AUTH_PASSWORD_VALIDATORS = [ +AUTH_PASSWORD_VALIDATORS = [ # Fix Line 103: E501 (by moving opening bracket) { - "NAME": ( # Fix Line 93: E501 line too long (using parentheses) + "NAME": ( # Fix Line 104 (previously 93): E501 (already wrapped) "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" ), # User similarity validator }, { - "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + "NAME": ( # Fix Line 108 (previously 106): E501 (wrapping string) + "django.contrib.auth.password_validation.MinimumLengthValidator" + ), }, { - "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + "NAME": ( # Fix Line 112 (previously 109): E501 (wrapping string) + "django.contrib.auth.password_validation.CommonPasswordValidator" + ), }, { - "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + "NAME": + "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -138,4 +143,6 @@ DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -STATICFILES_DIRS = [os.path.join(BASE_DIR, "frontend/static")] # Static files directory +STATICFILES_DIRS = [ # Fix Line 141 (originally 141 in current context): E501 (by moving opening bracket & comment) + os.path.join(BASE_DIR, "frontend/static") +] # Static files directory From c612177969aa45c741a89242aa85a4ec823f7cc5 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 20:14:19 -0400 Subject: [PATCH 25/36] Update app.js --- server/database/app.js | 117 +++++++++++++++++++++-------------------- 1 file changed, 59 insertions(+), 58 deletions(-) diff --git a/server/database/app.js b/server/database/app.js index ff9f50b982..f115b3a709 100644 --- a/server/database/app.js +++ b/server/database/app.js @@ -1,59 +1,60 @@ +/*jshint esversion: 8 */ // This line should already be at the top from previous fixes. + const express = require('express'); const mongoose = require('mongoose'); const fs = require('fs'); -const cors = require('cors') -const app = express() +const cors = require('cors'); // Corrected spacing +const app = express(); // Added semicolon const port = 3030; -app.use(cors()) -app.use(require('body-parser').urlencoded({ extended: false })); - -const reviews_data = JSON.parse(fs.readFileSync("reviews.json", 'utf8')); -const dealerships_data = JSON.parse(fs.readFileSync("dealerships.json", 'utf8')); +app.use(cors()); // Added semicolon +app.use(require('body-parser').urlencoded({ extended: false })); // Added semicolon -mongoose.connect("mongodb://mongo_db:27017/",{'dbName':'dealershipsDB'}); +const reviews_data = JSON.parse(fs.readFileSync("reviews.json", 'utf8')); // Added semicolon +const dealerships_data = JSON.parse(fs.readFileSync("dealerships.json", 'utf8')); // Added semicolon +mongoose.connect("mongodb://mongo_db:27017/", {'dbName': 'dealershipsDB'}); // Added semicolon and fixed spacing -const Reviews = require('./review'); +const Reviews = require('./review'); // Added semicolon -const Dealerships = require('./dealership'); +const Dealerships = require('./dealership'); // Added semicolon try { - Reviews.deleteMany({}).then(()=>{ - Reviews.insertMany(reviews_data['reviews']); - }); - Dealerships.deleteMany({}).then(()=>{ - Dealerships.insertMany(dealerships_data['dealerships']); - }); - + Reviews.deleteMany({}).then(() => { + Reviews.insertMany(reviews_data.reviews); // Fixed to dot notation: reviews_data['reviews'] -> reviews_data.reviews + }); + Dealerships.deleteMany({}).then(() => { + Dealerships.insertMany(dealerships_data.dealerships); // Fixed to dot notation: dealerships_data['dealerships'] -> dealerships_data.dealerships + }); + } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); + res.status(500).json({ error: 'Error fetching documents' }); } // Express route to home app.get('/', async (req, res) => { - res.send("Welcome to the Mongoose API") + res.send("Welcome to the Mongoose API"); // Added semicolon }); // Express route to fetch all reviews app.get('/fetchReviews', async (req, res) => { - try { - const documents = await Reviews.find(); - res.json(documents); - } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); - } + try { + const documents = await Reviews.find(); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch reviews by a particular dealer app.get('/fetchReviews/dealer/:id', async (req, res) => { - try { - const documents = await Reviews.find({dealership: req.params.id}); - res.json(documents); - } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); - } + try { + const documents = await Reviews.find({ dealership: req.params.id }); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch all dealerships @@ -61,49 +62,49 @@ app.get('/fetchDealers', async (req, res) => { try { const documents = await Dealerships.find(); res.json(documents); - } catch (error) { + } catch (error) { res.status(500).json({ error: 'Error fetching documents' }); - } + } }); // Express route to fetch Dealers by a particular state app.get('/fetchDealers/:state', async (req, res) => { - + }); // Express route to fetch dealer by a particular id app.get('/fetchDealer/:id', async (req, res) => { -//Write your code here + //Write your code here }); //Express route to insert review app.post('/insert_review', express.raw({ type: '*/*' }), async (req, res) => { - data = JSON.parse(req.body); - const documents = await Reviews.find().sort( { id: -1 } ) - let new_id = documents[0]['id']+1 - - const review = new Reviews({ - "id": new_id, - "name": data.name, - "dealership": data.dealership, - "review": data.review, - "purchase": data.purchase, - "purchase_date": data.purchase_date, - "car_make": data.car_make, - "car_model": data.car_model, // <-- Changed - "car_year": data.car_year // <-- Changed -}); + data = JSON.parse(req.body); // Added semicolon + const documents = await Reviews.find().sort({ id: -1 }); // Added semicolon + let new_id = documents[0].id + 1; // Fixed to dot notation: documents[0]['id'] -> documents[0].id + + const review = new Reviews({ + "id": new_id, + "name": data.name, + "dealership": data.dealership, + "review": data.review, + "purchase": data.purchase, + "purchase_date": data.purchase_date, + "car_make": data.car_make, + "car_model": data.car_model, + "car_year": data.car_year + }); - try { - const savedReview = await review.save(); - res.json(savedReview); - } catch (error) { - console.log(error); - res.status(500).json({ error: 'Error inserting review' }); - } + try { + const savedReview = await review.save(); + res.json(savedReview); + } catch (error) { + console.log(error); // Added semicolon + res.status(500).json({ error: 'Error inserting review' }); + } }); // Start the Express server app.listen(port, () => { - console.log(`Server is running on http://localhost:${port}`); + console.log(`Server is running on http://localhost:${port}`); }); From 1923275e27e0c23055eca5f556ceedeab8950d8e Mon Sep 17 00:00:00 2001 From: iintii Date: Wed, 23 Jul 2025 20:26:31 -0400 Subject: [PATCH 26/36] readjusted Line length --- server/djangoapp/models.py | 6 ++++-- server/djangoapp/populate.py | 14 +++++++++----- server/djangoapp/restapis.py | 4 ++-- server/djangoapp/views.py | 13 ++++++++----- 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index f93efbc169..9ad642d80e 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -53,8 +53,10 @@ class CarModel(models.Model): ] type = models.CharField(max_length=15, choices=CAR_TYPES, default="SUV") year = models.IntegerField( - default=2023, validators=[MaxValueValidator(2023), MinValueValidator(2015)] - ) + default=2023, + validators=[ + MaxValueValidator(2023), + MinValueValidator(2015)]) def __str__(self): return f"{self.car_make.name} - {self.name}" diff --git a/server/djangoapp/populate.py b/server/djangoapp/populate.py index 1df6368751..0f5a55cda1 100644 --- a/server/djangoapp/populate.py +++ b/server/djangoapp/populate.py @@ -13,8 +13,9 @@ def initiate(): car_make_instances = [] for data in car_make_data: car_make_instances.append( - CarMake.objects.create(name=data["name"], description=data["description"]) - ) + CarMake.objects.create( + name=data["name"], + description=data["description"])) # Create CarModel instances with the corresponding CarMake instances car_model_data = [ @@ -54,9 +55,12 @@ def initiate(): "year": 2023, "car_make": car_make_instances[1], }, - {"name": "A4", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, - {"name": "A5", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, - {"name": "A6", "type": "SUV", "year": 2023, "car_make": car_make_instances[2]}, + {"name": "A4", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, + {"name": "A5", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, + {"name": "A6", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, { "name": "Sorrento", "type": "SUV", diff --git a/server/djangoapp/restapis.py b/server/djangoapp/restapis.py index 6f890eb19a..cc05e40437 100644 --- a/server/djangoapp/restapis.py +++ b/server/djangoapp/restapis.py @@ -26,7 +26,7 @@ def get_request(endpoint, **kwargs): # Call get method of requests library with URL and parameters response = requests.get(request_url) return response.json() - except: + except BaseException: # If any error occurs print("Network exception occurred") @@ -54,7 +54,7 @@ def post_review(data_dict): response = requests.post(request_url, json=data_dict) print(response.json()) return response.json() - except: + except BaseException: print("Network exception occurred") diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index bbe17d5ca6..545b3a8755 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -77,11 +77,13 @@ def get_cars(request): car_models = CarModel.objects.select_related("car_make") cars = [] for car_model in car_models: - cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name}) + cars.append({"CarModel": car_model.name, + "CarMake": car_model.car_make.name}) return JsonResponse({"CarModels": cars}) -# Update the `get_dealerships` render list of dealerships all by default, particular state if state is passed +# Update the `get_dealerships` render list of dealerships all by default, +# particular state if state is passed def get_dealerships(request, state="All"): if state == "All": endpoint = "/fetchDealers" @@ -115,12 +117,13 @@ def get_dealer_reviews(request, dealer_id): def add_review(request): - if request.user.is_anonymous == False: + if not request.user.is_anonymous: data = json.loads(request.body) try: response = post_review(data) return JsonResponse({"status": 200}) - except: - return JsonResponse({"status": 401, "message": "Error in posting review"}) + except BaseException: + return JsonResponse( + {"status": 401, "message": "Error in posting review"}) else: return JsonResponse({"status": 403, "message": "Unauthorized"}) From 6fc0c6bfa72dbee1e51a7ad0d983f18346817259 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 20:48:20 -0400 Subject: [PATCH 27/36] Update settings.py --- server/djangoproj/settings.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index fa2dc09a42..02ba66c44c 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -27,11 +27,13 @@ # SECURITY WARNING: don't run with debug on in production! DEBUG = True -ALLOWED_HOSTS = [ # Fix Line 31 (originally 31 in the current context) +ALLOWED_HOSTS = [ "localhost", + # Fix Line 32 (previously 31/32 in past reports): E501 line too long "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai", ] -CSRF_TRUSTED_ORIGINS = [ # Fix Line 32 (originally 32 in the current context) +CSRF_TRUSTED_ORIGINS = [ + # Fix Line 35 (previously 32/35 in past reports): E501 line too long "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai" ] @@ -65,7 +67,7 @@ TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", - "DIRS": [ # Fix Line 64 (originally 64 in the current context) + "DIRS": [ os.path.join(BASE_DIR, "frontend/static") ], "APP_DIRS": True, @@ -93,19 +95,20 @@ } } -AUTH_PASSWORD_VALIDATORS = [ # Fix Line 103: E501 (by moving opening bracket) +AUTH_PASSWORD_VALIDATORS = [ { - "NAME": ( # Fix Line 104 (previously 93): E501 (already wrapped) + "NAME": ( + # Fix Line 99 (previously 93/104): E501 line too long (using parentheses) "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" ), # User similarity validator }, { - "NAME": ( # Fix Line 108 (previously 106): E501 (wrapping string) + "NAME": ( "django.contrib.auth.password_validation.MinimumLengthValidator" ), }, { - "NAME": ( # Fix Line 112 (previously 109): E501 (wrapping string) + "NAME": ( "django.contrib.auth.password_validation.CommonPasswordValidator" ), }, @@ -143,6 +146,8 @@ DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -STATICFILES_DIRS = [ # Fix Line 141 (originally 141 in current context): E501 (by moving opening bracket & comment) - os.path.join(BASE_DIR, "frontend/static") +STATICFILES_DIRS = [ + os.path.join( # Fix Line 146 (previously 141): E501 line too long + BASE_DIR, "frontend/static" + ) ] # Static files directory From 22eeb7b55cbf8f57e89f32fd83128f015cff8170 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:10:54 -0400 Subject: [PATCH 28/36] Update views.py --- server/djangoapp/views.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index 545b3a8755..07f5e8eaaf 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,18 +1,12 @@ # Uncomment the required imports before adding the code -from django.shortcuts import render -from django.http import HttpResponseRedirect, HttpResponse -from django.contrib.auth.models import User -from django.shortcuts import get_object_or_404, render, redirect -from django.contrib.auth import logout -from django.contrib import messages -from datetime import datetime - +rom django.shortcuts import render from django.http import JsonResponse from django.contrib.auth import login, authenticate import logging import json from django.views.decorators.csrf import csrf_exempt + from .populate import initiate from .models import CarMake, CarModel from .restapis import get_request, analyze_review_sentiments, post_review From 6d891ea1fb14f789173d879bf9e2f6558996f365 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:14:23 -0400 Subject: [PATCH 29/36] Update settings.py --- server/djangoproj/settings.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index 02ba66c44c..b63aec0a18 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -22,19 +22,25 @@ # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = "django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0" +SECRET_KEY = ( + "django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0" +) # SECURITY WARNING: don't run with debug on in production! DEBUG = True ALLOWED_HOSTS = [ "localhost", - # Fix Line 32 (previously 31/32 in past reports): E501 line too long - "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai", + ( # Fix Line 33: E501 line too long (splitting URL string) + "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01" + ".proxy.cognitiveclass.ai" + ), ] CSRF_TRUSTED_ORIGINS = [ - # Fix Line 35 (previously 32/35 in past reports): E501 line too long - "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai" + ( # Fix Line 37: E501 line too long (splitting URL string) + "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01" + ".proxy.cognitiveclass.ai" + ) ] REST_FRAMEWORK = { @@ -98,8 +104,10 @@ AUTH_PASSWORD_VALIDATORS = [ { "NAME": ( - # Fix Line 99 (previously 93/104): E501 line too long (using parentheses) - "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + # Fix Line 101: E501 (comment too long, shortened) + # UserAttributeSimilarityValidator (splitting string on line 102) + "django.contrib.auth.password_validation." # Fix Line 102: E501 (splitting string) + "UserAttributeSimilarityValidator" ), # User similarity validator }, { @@ -147,7 +155,7 @@ DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" STATICFILES_DIRS = [ - os.path.join( # Fix Line 146 (previously 141): E501 line too long + os.path.join( # This was previously line 146, which was fixed BASE_DIR, "frontend/static" ) ] # Static files directory From 2995c0a1053b0d7dc63778d269cd48bd92df9a97 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:15:58 -0400 Subject: [PATCH 30/36] Update models.py --- server/djangoapp/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index 9ad642d80e..5b4d6a24d0 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -1,7 +1,7 @@ # Uncomment the following imports before adding the Model code from django.db import models -from django.utils.timezone import now + from django.core.validators import MaxValueValidator, MinValueValidator From 0827034e9088d11170c3da22133d8d6b4a5dd476 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:16:45 -0400 Subject: [PATCH 31/36] Update settings.py --- server/djangoproj/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index b63aec0a18..366af3d546 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -105,8 +105,8 @@ { "NAME": ( # Fix Line 101: E501 (comment too long, shortened) - # UserAttributeSimilarityValidator (splitting string on line 102) - "django.contrib.auth.password_validation." # Fix Line 102: E501 (splitting string) + + "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ), # User similarity validator }, From 9b48275415b44b2de529fed6a433e9e034d1eeaf Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:42:52 -0400 Subject: [PATCH 32/36] Update settings.py --- server/djangoproj/settings.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index 366af3d546..f3a7fee52d 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -103,10 +103,8 @@ AUTH_PASSWORD_VALIDATORS = [ { - "NAME": ( - # Fix Line 101: E501 (comment too long, shortened) - - "django.contrib.auth.password_validation." + "NAME": ( + "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ), # User similarity validator }, From 432c9eefab7c301f81463183143b5715fd64c0d4 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:43:51 -0400 Subject: [PATCH 33/36] Update views.py --- server/djangoapp/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index 07f5e8eaaf..1223d7d457 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,6 +1,6 @@ # Uncomment the required imports before adding the code -rom django.shortcuts import render +from django.shortcuts import render from django.http import JsonResponse from django.contrib.auth import login, authenticate import logging From 7f5df0a2a59a45a9675eccc556967feae6fe4de1 Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:44:17 -0400 Subject: [PATCH 34/36] Update settings.py --- server/djangoproj/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index f3a7fee52d..d46d017952 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -103,7 +103,7 @@ AUTH_PASSWORD_VALIDATORS = [ { - "NAME": ( + "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ), # User similarity validator From bdf3ca049a03004018fc57c68938f3c212ead20f Mon Sep 17 00:00:00 2001 From: iintii <122311708+iintii@users.noreply.github.com> Date: Wed, 23 Jul 2025 21:46:46 -0400 Subject: [PATCH 35/36] Update views.py --- server/djangoapp/views.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index 1223d7d457..1ec9214fad 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,6 +1,5 @@ # Uncomment the required imports before adding the code -from django.shortcuts import render from django.http import JsonResponse from django.contrib.auth import login, authenticate import logging @@ -102,9 +101,9 @@ def get_dealer_reviews(request, dealer_id): endpoint = "/fetchReviews/dealer/" + str(dealer_id) reviews = get_request(endpoint) for review_detail in reviews: - response = analyze_review_sentiments(review_detail["review"]) - print(response) - review_detail["sentiment"] = response["sentiment"] + sentiment_response = analyze_review_sentiments(review_detail["review"]) + print(sentiment_response) + review_detail["sentiment"] = sentiment_response["sentiment"] return JsonResponse({"status": 200, "reviews": reviews}) else: return JsonResponse({"status": 400, "message": "Bad Request"}) @@ -114,7 +113,7 @@ def add_review(request): if not request.user.is_anonymous: data = json.loads(request.body) try: - response = post_review(data) + post_review(data) # No need to assign to 'response' if not used return JsonResponse({"status": 200}) except BaseException: return JsonResponse( From e0f74ac88be4465d57a75c86a85de8f64927d838 Mon Sep 17 00:00:00 2001 From: iintii Date: Wed, 23 Jul 2025 21:50:42 -0400 Subject: [PATCH 36/36] final --- server/djangoapp/views.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index 1ec9214fad..18720883fe 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -101,7 +101,8 @@ def get_dealer_reviews(request, dealer_id): endpoint = "/fetchReviews/dealer/" + str(dealer_id) reviews = get_request(endpoint) for review_detail in reviews: - sentiment_response = analyze_review_sentiments(review_detail["review"]) + sentiment_response = analyze_review_sentiments( + review_detail["review"]) print(sentiment_response) review_detail["sentiment"] = sentiment_response["sentiment"] return JsonResponse({"status": 200, "reviews": reviews}) @@ -113,7 +114,7 @@ def add_review(request): if not request.user.is_anonymous: data = json.loads(request.body) try: - post_review(data) # No need to assign to 'response' if not used + post_review(data) # No need to assign to 'response' if not used return JsonResponse({"status": 200}) except BaseException: return JsonResponse(