Reputation: 15
Python 3.8.3
asgiref 3.3.1
Django 2.2
django-crispy-forms 1.10.0
djangorestframework 3.11.1
Pillow 7.2.0
pip 19.2.3
psycopg2 2.8.6
pytz 2020.1
setuptools 41.2.0
sqlparse 0.3.1
Sorry, I'm not sure where there is an abnormality in a situation, can you mention me? Then I posted error information in stackoverflow and presented it with my code, the link is AttributeError: type object 'Product' has no attribute 'objects' , You can click the link to enter and watch...Thank you.
Everyone, help me think about the screen. After I clicked on the product I need add to car, an error appeared, and the product could not be added to my shopping cart. May I ask if this message appears. File "C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py", line 195, in updateItem** product = Product.objects.get(id=productId) AttributeError: type object'Product' has no attribute'objects'** Is it because views.py is damaged?
Because "POST /store/update_item/ HTTP/1.1" 500 59 the information came out a bit unexpectedly, after all, I didn’t mess with the program. I don’t know which side of the program affects QWQ.
Hope to mention me a bit, thank you very much.
遇到問題是:The problems encountered are:
product = Product.objects.get(id=productId)
AttributeError: type object 'Product' has no attribute 'objects'
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
February 22, 2021 - 13:09:19
Django version 2.2, using settings 'libshopapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[22/Feb/2021 13:09:22] "GET /store/ HTTP/1.1" 200 32153
Action: add
Product: 135
1.
Traceback (most recent call last):
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py", line 195, in updateItem**
product = Product.objects.get(id=productId)
AttributeError: type object 'Product' has no attribute 'objects'**
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\python\Python38\lib\site-packages\django\utils\deprecation.py", line 94, in __call__
response = response or self.get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 36, in inner
response = response_for_exception(request, exc)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
2.
Traceback (most recent call last):
File "D:\python\Python38\lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "D:\python\Python38\lib\site-packages\django\contrib\staticfiles\handlers.py", line 65, in __call__
return self.application(environ, start_response)
File "D:\python\Python38\lib\site-packages\django\core\handlers\wsgi.py", line 141, in __call__
response = self.get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 75, in get_response
response = self._middleware_chain(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 36, in inner
response = response_for_exception(request, exc)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 125, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "D:\python\Python38\lib\site-packages\django\views\debug.py", line 94, in technical_500_response
html = reporter.get_traceback_html()
File "D:\python\Python38\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
t = DEBUG_ENGINE.from_string(fh.read())
UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 9735: illegal multibyte sequence
**[22/Feb/2021 13:09:27] "POST /store/update_item/ HTTP/1.1" 500 59**
請幫忙看看,謝謝? please help to see, thank you.
//////////////////////////////////////////////////////code//////////////////////////////////////////////
/// store / models.py ///
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=200)
content = models.TextField(default='')
price = models.DecimalField(max_digits=7, decimal_places=2)
digital = models.BooleanField(default=False, null=True, blank=True)
draft = models.BooleanField(default=False)
image = models.ImageField(
upload_to=imgs,
null=True,
blank=True,
width_field="width_field",
height_field="height_field",
)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
products = ProductManage()
def __unicode__(self):
return self.name
def __str__(self):
return self.name
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
def get_absolute_url(self):
return reverse('store:detail', kwargs={'id': self.id})
class Meta:
ordering = ["-timestamp", "-updated"]
/// home / urls.py ///
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
# path('order/', views.order, name='order'),
path('social/', views.socialview, name='social'),
path('about/', views.aboutview, name='about'),
path('contact/', views.contact, name='contact'),
path('', views.index, name='index'),
]
/// store / urls.py ///
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
# Leave as empty string for base url
path('', views.store, name='store'),
path('cart/', views.cart, name='cart'),
path('create/', views.productCreate, name='create'),
path('<int:id>/', views.productDetail, name='detail'),
path('<int:id>/update/', views.productUpdate, name='update'),
path('<int:id>/delete/', views.productDelete, name='delete'),
path('checkout/', views.checkout, name='checkout'),
path('update_item/', views.updateItem, name='update_item'),
# path('update_item/', views.updateItem, name='update_item'),
path('process_order/', views.processOrder, name='process_order'),
path('searchbar/', views.searchbar, name='searchbar'),
]
/// store / views.py ///
import datetime
import json
from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductForms
from .models import Product
from .utils import cartData, guestOrder
from django.utils import timezone
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)
/// cart.js ///
question: "POST /store/update_item/ HTTP/1.1" 500 59
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/store/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
/// froms.py ///
from django import forms
from store.models import Product, RegistrationData
class ProductForms(forms.ModelForm):
class Meta:
model = Product
fields = [
'name',
'price',
'digital',
'image',
'width_field',
'height_field',
'content',
]
Upvotes: 0
Views: 7456
Reputation: 15
well i recently had that same problem, in class Meta of my model i set abstract = True. Make sure you did not do the same and make sure a view name or task name is not the same as your Model name
Upvotes: 0
Reputation: 62
make sure you did not define class name or function or varible with same name
Upvotes: 0
Reputation: 482
where you import your models.py in your views.py? just import your models file in your views and then you will be able to access your models classes in your views file. something just like this:
from <models_directory> import models
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
product = models.Product.objects.get(id=productId)
# and other...
Upvotes: 1