"Uncaught ReferenceError: user is not defined at" in Django
"Uncaught ReferenceError: user is not defined at" in Django
我正在尝试按照 YouTube 中 Dennis Ivy 的指南制作一个电子商务网站。但是在结帐表单中应用一些逻辑时,我遇到了一个错误,提示“未捕获的引用错误:用户未定义在”。
["Uncaught ReferenceError: user is not defined at" in the console]
如果用户不是“AnonymousUser”,我想做的是删除 'user-info'。并删除 'form' 如果您不需要运送产品(数字)并且用户不是“AnonymousUser”仅显示 'payment-info'.
这是 checkout.html 代码:
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-lg-6">
<div class="box-element" id="form-wrapper">
<form id="form">
<div id="user-info">
<div class="form-field">
<input required class="form-control" type="text" name="name" placeholder="Name..">
</div>
<div class="form-field">
<input required class="form-control" type="email" name="email" placeholder="Email..">
</div>
</div>
<div id="shipping-info">
<hr>
<p>Shipping Information:</p>
<hr>
<div class="form-field">
<input class="form-control" type="text" name="address" placeholder="Address..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="city" placeholder="City..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="state" placeholder="State..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="zipcode" placeholder="Zip code..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="country" placeholder="Zip code..">
</div>
</div>
<hr>
<input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue">
</form>
</div>
<br>
<div class="box-element hidden" id="payment-info">
<small>Paypal Options</small>
<button id="make-payment">Make Payment</button>
</div>
</div>
<div class="col-lg-6">
<div class="box-element">
<a class="btn btn-outline-dark" href="{% url 'cart' %}">← Back to Cart</a>
<hr>
<h3>Order Summary</h3>
<hr>
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image" 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 %}
这是 models.py 文件:
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
这是 views.py 文件:
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)
我认为checkout.html底部的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');
}
我怎样才能摆脱那个错误并应用我想要的逻辑?
就像您在您看来所做的那样,检查用户是否匿名的方法是使用 request.user.is_authenticated
,而不是检查用户是否等于 字符串'AnonymousUser'。因此,将 HTML 和 JavaScript 中的所有 if user != 'AnonymousUser':
实例替换为 if request.user.is_authenticated
甚至 user.is_authenticated
。查看关于此的 docs。
就新错误而言,它可能只是意味着您在 Javascript 中使用了错误的语法。这是需要完成的方法(这只是一个示例,您需要替换所有这样的实例:
if ({% request.user.is_authenticated %}){
document.getElementById('user-info').innerHTML = ''
}
注意 {% %}
告诉 Django 用变量替换其中的内容,在本例中 request.user.is_authenticated
。
在 checkout.html 中将 AnonymousUser 更改为用户 !='False' 它将起作用。
var shipping = '{{order.shipping}}'
var total = '{{order.get_cart_total|floatformat:2}}'
如果(运费 == 'False'){
document.getElementById('shipping-info').innerHTML = ''
}
**如果(用户!= "False")**{
document.getElementById('user-info').innerHTML = ''
}
**如果(运费 == 'False' && 用户 == "True")**{
//如果用户已登录且发货为假,则隐藏整个表单
document.getElementById('form-wrapper').classList.add('hidden');
//如果登录用户想要购买不需要运输的商品,则显示付款
document.getElementById('payment-info').classList.remove('hidden');
}
变量形式 = document.getElementById('form')
form.addEventListener('submit', 函数(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', 函数(e){
提交表单数据()
})
函数 submitFormData(){
console.log('Payment button clicked')}
我正在尝试按照 YouTube 中 Dennis Ivy 的指南制作一个电子商务网站。但是在结帐表单中应用一些逻辑时,我遇到了一个错误,提示“未捕获的引用错误:用户未定义在”。
["Uncaught ReferenceError: user is not defined at" in the console]
如果用户不是“AnonymousUser”,我想做的是删除 'user-info'。并删除 'form' 如果您不需要运送产品(数字)并且用户不是“AnonymousUser”仅显示 'payment-info'.
这是 checkout.html 代码:
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-lg-6">
<div class="box-element" id="form-wrapper">
<form id="form">
<div id="user-info">
<div class="form-field">
<input required class="form-control" type="text" name="name" placeholder="Name..">
</div>
<div class="form-field">
<input required class="form-control" type="email" name="email" placeholder="Email..">
</div>
</div>
<div id="shipping-info">
<hr>
<p>Shipping Information:</p>
<hr>
<div class="form-field">
<input class="form-control" type="text" name="address" placeholder="Address..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="city" placeholder="City..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="state" placeholder="State..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="zipcode" placeholder="Zip code..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="country" placeholder="Zip code..">
</div>
</div>
<hr>
<input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue">
</form>
</div>
<br>
<div class="box-element hidden" id="payment-info">
<small>Paypal Options</small>
<button id="make-payment">Make Payment</button>
</div>
</div>
<div class="col-lg-6">
<div class="box-element">
<a class="btn btn-outline-dark" href="{% url 'cart' %}">← Back to Cart</a>
<hr>
<h3>Order Summary</h3>
<hr>
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image" 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 %}
这是 models.py 文件:
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
这是 views.py 文件:
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)
我认为checkout.html底部的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');
}
我怎样才能摆脱那个错误并应用我想要的逻辑?
就像您在您看来所做的那样,检查用户是否匿名的方法是使用 request.user.is_authenticated
,而不是检查用户是否等于 字符串'AnonymousUser'。因此,将 HTML 和 JavaScript 中的所有 if user != 'AnonymousUser':
实例替换为 if request.user.is_authenticated
甚至 user.is_authenticated
。查看关于此的 docs。
就新错误而言,它可能只是意味着您在 Javascript 中使用了错误的语法。这是需要完成的方法(这只是一个示例,您需要替换所有这样的实例:
if ({% request.user.is_authenticated %}){
document.getElementById('user-info').innerHTML = ''
}
注意 {% %}
告诉 Django 用变量替换其中的内容,在本例中 request.user.is_authenticated
。
在 checkout.html 中将 AnonymousUser 更改为用户 !='False' 它将起作用。
var shipping = '{{order.shipping}}' var total = '{{order.get_cart_total|floatformat:2}}' 如果(运费 == 'False'){ document.getElementById('shipping-info').innerHTML = '' } **如果(用户!= "False")**{ document.getElementById('user-info').innerHTML = '' } **如果(运费 == 'False' && 用户 == "True")**{ //如果用户已登录且发货为假,则隐藏整个表单 document.getElementById('form-wrapper').classList.add('hidden'); //如果登录用户想要购买不需要运输的商品,则显示付款 document.getElementById('payment-info').classList.remove('hidden'); } 变量形式 = document.getElementById('form') form.addEventListener('submit', 函数(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', 函数(e){ 提交表单数据() }) 函数 submitFormData(){ console.log('Payment button clicked')}