DJANGO:类型错误:需要一个整数

时间:2021-03-27 05:53:23

标签: python python-3.x django django-models

请帮忙! 我是 DJANGO 的新手,几乎没有编码经验。我正在完成一个涉及构建购物车的教程。当用户导航到 localhost/cart/cart 时,代码应创建一个购物车。

我之前修复了一个错误,但修复似乎揭示了另一个问题。尽管购物车已加载,但在管理门户中并未创建购物车。尝试从 DJANGO 管理 UI 手动创建购物车时,单击添加会出现以下错误:

回溯错误

Internal Server Error: /admin/cart/cart/add/
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\env\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1580, in _changeform_view
    self.save_model(request, new_object, form, not add)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1093, in save_model
    obj.save()
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\base.py", line 790, in save_base
    updated = self._save_table(
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\base.py", line 933, in _do_insert
    return manager._insert(
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\sql\compiler.py", line 1339, in as_sql
    value_rows = [
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\sql\compiler.py", line 1281, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\models\fields\__init__.py", line 1512, in get_db_prep_save
    return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\backends\base\operations.py", line 523, in adapt_decimalfield_value
    return utils.format_number(value, max_digits, decimal_places)
  File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\db\backends\utils.py", line 233, in format_number
    context.prec = max_digits
TypeError: an integer is required

cart/models.py

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
class CartManager(models.Manager):
    def new_or_get(self, request):
        cart_id = request.session.get("cart_id", default= None)
        qs = self.get_queryset().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, 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)

购物车/views.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)
    print('cart_obj:', cart_obj)
    return render(request, "home.html", {})
'''
__cart/admin.py__

from django.contrib import admin
from .models import cart

admin.site.register(cart)

settings.py

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = ''

DEBUG = True

ALLOWED_HOSTS = []
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'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


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',
    },
]



LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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 = ""

0 个答案:

没有答案