I am trying to make an e-commerce website by following the guide of Dennis Ivy in YouTube. But in applying some logic in the checkout form, I've been facing an error that says "Uncaught ReferenceError: user is not defined at".
["Uncaught ReferenceError: user is not defined at" in the console]
What I want to do is remove the 'user-info' if the user is not "AnonymousUser". And remove the 'form' if you don't need to ship the products (digital) and the user is not "AnonymousUser" to only show the 'payment-info'.
Here's the checkout.html code:
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div >
<div >
<div id="form-wrapper">
<form id="form">
<div id="user-info">
<div >
<input required type="text" name="name" placeholder="Name..">
</div>
<div >
<input required type="email" name="email" placeholder="Email..">
</div>
</div>
<div id="shipping-info">
<hr>
<p>Shipping Information:</p>
<hr>
<div >
<input type="text" name="address" placeholder="Address..">
</div>
<div >
<input type="text" name="city" placeholder="City..">
</div>
<div >
<input type="text" name="state" placeholder="State..">
</div>
<div >
<input type="text" name="zipcode" placeholder="Zip code..">
</div>
<div >
<input type="text" name="country" placeholder="Zip code..">
</div>
</div>
<hr>
<input id="form-button" type="submit" value="Continue">
</form>
</div>
<br>
<div id="payment-info">
<small>Paypal Options</small>
<button id="make-payment">Make Payment</button>
</div>
</div>
<div >
<div >
<a href="{% url 'cart' %}">← Back to Cart</a>
<hr>
<h3>Order Summary</h3>
<hr>
{% for item in items %}
<div >
<div style="flex:2"><img src="{{item.product.imageURL}}"></div>
<div style="flex:2"><p>{{item.product.name}}</p></div>
<div style="flex:1"><p>₱{{item.product.price|floatformat:2}}</p></div>
<div style="flex:1"><p>x{{item.quantity}}</p></div>
</div>
{% endfor %}
<h5>Items: {{order.get_cart_items}}</h5>
<h5>Total: ₱{{order.get_cart_total|floatformat:2}}</h5>
</div>
</div>
</div>
<script type="text/javascript">
var shipping = '{{order.shipping}}'
if(shipping == 'False'){
document.getElementById('shipping-info').innerHTML = ''
}
if (user != 'AnonymousUser'){
document.getElementById('user-info').innerHTML = ''
}
if (shipping == 'False' && user != 'AnonymousUser'){
//Hide entire form if user is logged in and shipping is false
document.getElementById('form-wrapper').classList.add('hidden');
//Show payment if logged in user wants to buy an item that does not require shipping
document.getElementById('payment-info').classList.remove('hidden');
}
var form = document.getElementById('form')
form.addEventListener('submit', function(e){
e.preventDefault()
console.log('Form Submitted...')
document.getElementById('form-button').classList.add("hidden");
document.getElementById('payment-info').classList.remove("hidden");
})
document.getElementById('make-payment').addEventListener('click', function(e){
submitFormData()
})
function submitFormData(){
console.log('Payment button clicked')
}
</script>
{% endblock content %}
Here's the models.py file:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=20, null=True)
def __str__(self):
return str(self.id)
@property
def shipping(self):
shipping = False
orderitems = self.orderitem_set.all()
for i in orderitems:
if i.product.digital == False:
shipping = True
return shipping
@property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
@property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
@property
def get_total(self):
total = self.product.price * self.quantity
return total
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zip = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
Here's the views.py file:
from itertools import product
from django.http import JsonResponse
from django.shortcuts import render
from .models import *
import json
def store(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping': False}
cartItems = order['get_cart_items']
products = Product.objects.all()
context = {'products':products, 'items':items, 'cartItems': cartItems}
return render(request, 'store/store.html', context)
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping': False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems': cartItems}
return render(request, 'store/cart.html', context)
def checkout(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping': False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems': cartItems}
return render(request, 'store/checkout.html', context)
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
I think the JavaScript at the bottom of checkout.html is asking for the user in this part:
var shipping = '{{order.shipping}}'
if(shipping == 'False'){
document.getElementById('shipping-info').innerHTML = ''
}
if (user != 'AnonymousUser'){
document.getElementById('user-info').innerHTML = ''
}
if (shipping == 'False' && user != 'AnonymousUser'){
//Hide entire form if user is logged in and shipping is false
document.getElementById('form-wrapper').classList.add('hidden');
//Show payment if logged in user wants to buy an item that does not require shipping
document.getElementById('payment-info').classList.remove('hidden');
}
How can I get rid of that error and apply the logic that I want?
CodePudding user response:
Just like you did in your view, the way to check to see if a user is anonymous or not is to use the request.user.is_authenticated
, instead of checking to see if the user equals the string 'AnonymousUser'. So replace all instances of if user != 'AnonymousUser':
in your HTML and JavaScript with if request.user.is_authenticated
or perhaps even user.is_authenticated
. Check out the docs on this.
Now as far as the new error, it might just mean you're using the wrong syntax in the Javascript. Here's how it needs to be done (this is only an example, you'll need to replace all instances like this one:
if ({% request.user.is_authenticated %}){
document.getElementById('user-info').innerHTML = ''
}
Note the {% %}
to tell Django to replace the contents within with the variable, in this case request.user.is_authenticated
.