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
对不起,我不知道情况哪里有异常,你能不能告诉我,然后我在stackoverflow中发布了错误信息,并用我的代码呈现出来,链接是AttributeError:类型对象'Product'没有属性'objects',您可以点击链接进入并观看...谢谢。
大家帮我想一想屏幕,我点击需要添加到汽车的产品后出现错误,产品无法添加到我的购物车,请问是否出现此消息,文件“C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py”,第195行,在updateItemproduct = Product.objects.get(id=productId)AttributeError:类型对象“Product”没有属性“objects”是否因为views.py已损坏?
因为“POST /store/update_item/ HTTP/1.1”500 59信息出来的有点意外,毕竟我没有把程序搞乱,不知道程序哪一边影响QWQ。
希望能提到我一点,非常感谢。
遇到問題是: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.
/////
///商店/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"]
///首页/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'),
]
///商店/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'),
]
///商店/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)
///购物车. js///
问题:“POST /存储/更新项目/ 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',
]
3条答案
按热度按时间b4qexyjb1#
当你在你的www.example.com中导入你models.pyviews.py?时,只需在你的视图中导入你的models文件,然后你就可以在你的视图文件中访问你的models类了.就像这样:
h22fl7wq2#
确保你没有定义类名或函数或变量同名
hwamh0ep3#
我最近也遇到了同样的问题,在我的模型的 meta类中我设置了abstract = True。2确保你没有做同样的事情,并且确保视图名或者任务名和你的模型名不一样