Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newbranch #128

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions server/djangoapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
# 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 = [
# # path for registration
path('register/', views.registration, name='register'),

# path for login
# path(route='login', view=views.login_user, name='login'),
path(route='login', view=views.login_user, name='login'),

# path for dealer reviews view
path('dealer/<int:dealer_id>/reviews/', views.get_dealer_reviews, name='get_dealer_reviews'),

# path for add a review view

path('add_review/', views.add_review, name='add_review'),

path('logout/', views.logout_request, name='logout'),
path('dealer/<int:dealer_id>/', views.get_dealer_details, name='get_dealer_details'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
106 changes: 85 additions & 21 deletions server/djangoapp/views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# 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


# Get an instance of a logger
Expand All @@ -39,27 +39,91 @@ def login_user(request):
return JsonResponse(data)

# Create a `logout_request` view to handle sign out request
# def logout_request(request):
# ...
def logout_request(request):
if request.method == 'POST':
logout(request)
data = {"message": "Successfully logged out", "userName": ""}
return JsonResponse(data)
else:
return JsonResponse({"error": "Invalid request method"}, status=400)

# Create a `registration` view to handle sign up request
# @csrf_exempt
# def registration(request):
# ...
@csrf_exempt
def registration(request):
if request.method == 'POST':
try:
# Parse the incoming JSON data
data = json.loads(request.body)
username = data.get('userName')
password = data.get('password')
first_name = data.get('firstName')
last_name = data.get('lastName')
email = data.get('email')

# Check if any fields are missing
if not all([username, password, first_name, last_name, email]):
return JsonResponse({"error": "Missing required fields"}, status=400)

# Check if the username already exists
if User.objects.filter(username=username).exists():
return JsonResponse({"error": "Username already exists"}, status=400)

# Check if the email already exists
if User.objects.filter(email=email).exists():
return JsonResponse({"error": "Email already registered"}, status=400)

# Create a new user
user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, password=password, email=email)

# Log the user in after registration
login(request, user)

# Return successful registration
return JsonResponse({"userName": username, "status": "Authenticated"}, status=201)

except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON format"}, status=400)

return JsonResponse({"error": "Invalid request method"}, status=405)

# # Update the `get_dealerships` view to render the index page with
# a list of dealerships
# def get_dealerships(request):
# ...
def get_dealerships(request):
dealerships = [
{'id': 1, 'name': 'Dealer One', 'location': 'City A'},
{'id': 2, 'name': 'Dealer Two', 'location': 'City B'},
# Add more dealership data or fetch from API/DB
]

return render(request, 'index.html', {'dealerships': dealerships})

# Create a `get_dealer_reviews` view to render the reviews of a dealer
# def get_dealer_reviews(request,dealer_id):
# ...
def get_dealer_reviews(request, dealer_id):
# Simulate dealer reviews or fetch from API/DB
reviews = [
{'review': 'Great service!', 'rating': 5, 'dealer_id': dealer_id},
{'review': 'Not bad', 'rating': 3, 'dealer_id': dealer_id},
]

return render(request, 'dealer_reviews.html', {'reviews': reviews, 'dealer_id': dealer_id})
# Create a `get_dealer_details` view to render the dealer details
# def get_dealer_details(request, dealer_id):
# ...
def get_dealer_details(request, dealer_id):
# Simulate dealer details or fetch from API/DB
dealer = {'id': dealer_id, 'name': 'Dealer One', 'location': 'City A'}

return render(request, 'dealer_details.html', {'dealer': dealer})

# Create a `add_review` view to submit a review
# def add_review(request):
# ...
def add_review(request):
if request.method == 'POST':
dealer_id = request.POST.get('dealer_id')
review = request.POST.get('review')
rating = request.POST.get('rating')

# Simulate saving the review (normally save it in DB or call an API)
print(f'Review: {review}, Rating: {rating}, Dealer ID: {dealer_id}')

return redirect('get_dealer_reviews', dealer_id=dealer_id) # Redirect to reviews page

# Render the review form if it's a GET request
return render(request, 'add_review.html')
19 changes: 15 additions & 4 deletions server/djangoproj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
CSRF_TRUSTED_ORIGINS = []
ALLOWED_HOSTS=['localhost','https://swapnilpawa2-8000.theianext-1-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai/']
CSRF_TRUSTED_ORIGINS = [
'https://swapnilpawa2-8000.theianext-1-labs-prod-misc-tools-us-east-0.proxy.cognitiveclass.ai',
]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
Expand All @@ -48,6 +50,7 @@
]

MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
Expand All @@ -61,7 +64,11 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [
os.path.join(BASE_DIR, 'frontend/static'),
os.path.join(BASE_DIR, 'frontend/build'),
os.path.join(BASE_DIR, 'frontend/build/static'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down Expand Up @@ -134,5 +141,9 @@

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

STATICFILES_DIRS = []
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend/static'),
os.path.join(BASE_DIR, 'frontend/build'),
os.path.join(BASE_DIR, 'frontend/build/static'),
]

4 changes: 4 additions & 0 deletions server/djangoproj/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@
path('admin/', admin.site.urls),
path('djangoapp/', include('djangoapp.urls')),
path('', TemplateView.as_view(template_name="Home.html")),
path('about/', TemplateView.as_view(template_name="About.html")),
path('contact/', TemplateView.as_view(template_name="Contact.html")),
path('login/', TemplateView.as_view(template_name="index.html")),
path('register/', TemplateView.as_view(template_name="index.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
28 changes: 25 additions & 3 deletions server/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions server/frontend/src/App.js
Original file line number Diff line number Diff line change
@@ -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 (
<Routes>
<Route path="/login" element={<LoginPanel />} />
<Route path="/register" element={<Register/>} />
</Routes>
);
}
Expand Down
98 changes: 98 additions & 0 deletions server/frontend/src/components/Register/Register.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
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 = () => {

const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setlastName] = useState("");


const gohome = ()=> {
window.location.href = window.location.origin;
}

const register = async (e) => {
e.preventDefault();

let register_url = window.location.origin+"/djangoapp/register/";

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) {
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(
<div className="register_container" style={{width: "50%"}}>
<div className="header" style={{display: "flex",flexDirection: "row", justifyContent: "space-between"}}>
<span className="text" style={{flexGrow:"1"}}>SignUp</span>
<div style={{display: "flex",flexDirection: "row", justifySelf: "end", alignSelf: "start" }}>
<a href="/" onClick={()=>{gohome()}} style={{justifyContent: "space-between", alignItems:"flex-end"}}>
<img style={{width:"1cm"}} src={close_icon} alt="X"/>
</a>
</div>
<hr/>
</div>

<form onSubmit={register}>
<div className="inputs">
<div className="input">
<img src={user_icon} className="img_icon" alt='Username'/>
<input type="text" name="username" placeholder="Username" className="input_field" onChange={(e) => setUserName(e.target.value)}/>
</div>
<div>
<img src={user_icon} className="img_icon" alt='First Name'/>
<input type="text" name="first_name" placeholder="First Name" className="input_field" onChange={(e) => setFirstName(e.target.value)}/>
</div>

<div>
<img src={user_icon} className="img_icon" alt='Last Name'/>
<input type="text" name="last_name" placeholder="Last Name" className="input_field" onChange={(e) => setlastName(e.target.value)}/>
</div>

<div>
<img src={email_icon} className="img_icon" alt='Email'/>
<input type="email" name="email" placeholder="email" className="input_field" onChange={(e) => setEmail(e.target.value)}/>
</div>

<div className="input">
<img src={password_icon} className="img_icon" alt='password'/>
<input name="psw" type="password" placeholder="Password" className="input_field" onChange={(e) => setPassword(e.target.value)}/>
</div>

</div>
<div className="submit_panel">
<input className="submit" type="submit" value="Register"/>
</div>
</form>
</div>
)
}

export default Register;
Loading