我是 DJANGO 的新手,编码经验有限。
我正在学习一个涉及构建购物车的 DJANGO 教程。我收到:前端需要一个类型错误整数;以及当我尝试手动创建购物车时,管理门户中不可调用的类型错误 bool 对象。
我认为教程中的代码有点过时,但我有限的经验意味着我尝试的任何更改都会导致更多错误。
代码如下: #追溯
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib as mpl
# Set plotting style
plt.style.use('seaborn-white')
dz=[]
z0 = np.array([ 1., 3., 11., 8., 7., 6., 6., 6., 5., 4.,
3., 11., 10., 1., 1., 7., 1., 3., 11., 8.,
8., 7., 6., 6., 1., 1., 7., 1.,])
dz.append(z0)
z1 =[ 5., 5., 8., 4., 2., 0., 0., 0., 0., 0., 0.,
1., 6., 5., 7., 2., 1., 3., 11., 8., 8., 7., 6., 6.,
1., 1., 7., 1.,]
dz.append(z1)
z2 =[ 15., 5., 8., 2., 0., 0., 0., 0., 0., 0., 0.,
3., 5., 2., 7., 2., 1., 3., 11., 8., 8., 7., 6., 6.,
1., 1., 7., 1.,]
dz.append(z2)
_zpos = z0*0
xlabels = pd.Index(['X01', 'X02', 'X03', 'X04'], dtype='object')
ylabels = pd.Index(['Y01', 'Y02', 'Y03', 'Y04', 'Y05', 'Y06', 'Y07'], dtype='object')
x = np.arange(xlabels.shape[0])
y = np.arange(ylabels.shape[0])
x_M, y_M = np.meshgrid(x, y, copy=False)
fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(111, projection='3d')
ax.set_box_aspect((1, 3.5, 1))
plt.gca().view_init(15, 20)
ls = mpl.colors.LightSource(azdeg=30, altdeg=10)
# Making the intervals in the axes match with their respective entries
ax.w_xaxis.set_ticks(x + 0.5/2.)
ax.w_yaxis.set_ticks(y + 0.5/2.)
# Renaming the ticks as they were before
ax.w_xaxis.set_ticklabels(xlabels)
ax.w_yaxis.set_ticklabels(ylabels)
# Labeling the 3 dimensions
ax.set_xlabel('X label')
ax.set_ylabel('Y label')
ax.set_zlabel('Z label')
# Choosing the range of values to be extended in the set colormap
values = np.linspace(0.2, 1., x_M.ravel().shape[0])
# Selecting an appropriate colormap
colors = ['#FFC04C', 'blue', '#3e9a19',
'#599be5','#bf666f','#a235bf','#848381','#fb90d6','#fb9125']
# Increase the number of segment to 3 by changing the X in 'range(X)' to 3.
for i in range(3):
ax.bar3d(x_M.ravel(), y_M.ravel(), _zpos, dx=0.2, dy=0.1, dz=dz[i],
color=colors[i], lightsource=ls)
_zpos += dz[i]
Segment1_proxy = plt.Rectangle((0, 0), 1, 1, fc="#FFC04C")
Segment2_proxy = plt.Rectangle((0, 0), 1, 1, fc="blue")
Segment3_proxy = plt.Rectangle((0, 0), 1, 1, fc="#3e9a19")
ax.legend([Segment1_proxy,
Segment2_proxy,
Segment3_proxy],['Segment1',
'Segment2',
'Segment3'
])
plt.show()
Internal Server Error: /cart/cart/
Traceback (most recent call last):
File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\views.py", line 13, in cart_home
cart_obj = cart.objects.new_or_get(request)
File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\models.py", line 11, in new_or_get
qs = self.getqueryset().filter(id=cart_id)
AttributeError: 'CartManager' object has no attribute 'getqueryset'
[27/Mar/2021 10:49:42] "GET /cart/cart/ HTTP/1.1" 500 71680
#cart/admin.py
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY =
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'store',
'patients',
'ckeditor',
'cart',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'pharmamart.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / ''],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pharmamart.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATICFILES_DIRS = [
BASE_DIR / "static",
]
LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = ""
from django.contrib import admin
from .models import cart
admin.site.register(cart)
from django.db import models
from django.conf import settings
from store.models import product, customer
from django.contrib.auth.models import User
#User = settings.AUTH_USER.MODEL# if included it throws an error 'settings not defined'
class CartManager(models.Manager):
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = self.getqueryset().filter(id=cart_id)
if qs.count()==1:
new_obj = False
cart_obj = qs.first()
if request.user.is_authenticated() and cart_obj.user is None:
cart_obj-save()
else:
cart_obj = cart.objects.new(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
def new(self, user = None):
user_obj = None
if user is not None:
if user is authenticated():
user_obj = user
return self.model.objects.create(user=user_obj)
class cart(models.Model):
user = models.ForeignKey(User, related_name = "user", blank = True, null=True, on_delete=models.CASCADE)
product = models.ManyToManyField('store.product')
total = models.DecimalField(default = 0.0, max_digits = 50.00, decimal_places = 2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now=True)
objects = CartManager()
def __str__(self):
return str(self.id)
购物车/urls.py
from django.shortcuts import render
from django.contrib import admin
from django.contrib.auth.models import User
from .models import cart
# Create your views here.
#def cart_create(user=None):
# cart_obj = cart.objects.create(user = None)
# print('New Cart created')
# return cart_obj
def cart_home(request):
cart_obj = cart.objects.new_or_get(request)
return render(request, "home.html", {})
感谢任何有关修改代码以显示我的错误的帮助。
交流