从模型中获取实例以保存到foreignkey字段

时间:2017-03-21 05:07:37

标签: python django django-models django-forms

我真的不明白这个实例暗示的是什么

"无法分配" 15":" Cart.Product_ID"必须是"产品" 。实例"

" 15"是Model.Product的主键,我想将它插入到Model.Cart

views.py

    def post(self, request, *args, **kwargs):
        form = TempCart(request.POST)
        if form.is_valid():
            VarProductId = Product.objecrs.get(PId="Product_ID")
            VarHowMany = request.POST.get('HowMany')
            VarDateSubmit = request.POST.get('DateSubmit')
            Cart_obj = Cart(Product_ID = VarProductId, HowMany = VarHowMany, DateSubmit = VarDateSubmit)
            Cart_obj.save()

            return HttpResponseRedirect('/Catalogue')

models.py

class Product(models.Model):
    PId = models.AutoField(primary_key=True)
    # and other fields

class Cart(models.Model):
    Product_ID = models.ForeignKey(Product,  on_delete=models.CASCADE)
    HowMany = models.PositiveIntegerField(default=0)
    DateSubmit = models.DateTimeField(default=datetime.now)

HTML

<form method="post" action="" id="CartInput"> {% csrf_token %}
    <div>
        <input name="Product_ID" type="hidden" value="{{ Product.pk }}" >
        <input name="HowMany" type="number" value="1" id="HowMany" >
        {{ CartForm.DateSubmit }}
    </div>
    <div>
        <input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart">
    </div>
</form>
我在这里错过了什么吗? 也许我必须保存Product_ID(foreignkey)的整个查询集?

提前致谢

干杯

编辑:

不知道这是否有帮助

ValueError at /Catalogue/
Cannot assign "'14'": "Cart.Product_ID" must be a "Product" instance.
Request Method: POST
Request URL:    http://127.0.0.1:8000/Catalogue/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:    
Cannot assign "'14'": "Cart.Product_ID" must be a "Product" instance.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\db\models\fields\related_descriptors.py in __set__, line 211
Python Executable:  C:\Users\User\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.0
Python Path:    
['C:\\Users\\User\\PycharmProjects\\Wildcard91\\Wildcard91',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\lib',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages',
 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages\\django-1.10.5-py3.6.egg']
Server time:    Tue, 21 Mar 2017 15:36:04 +0700
Traceback Switch back to interactive view


Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/Catalogue/

Django Version: 1.10.5
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.postgres',
 'Shop.apps.ShopConfig']
Installed 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']



Traceback:

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\views\generic\base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "C:\Users\User\PycharmProjects\Wildcard91\Wildcard91\Shop\views.py" in post
  180.         if form.is_valid():

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\forms\forms.py" in is_valid
  169.         return self.is_bound and not self.errors

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\forms\forms.py" in errors
  161.             self.full_clean()

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\forms\forms.py" in full_clean
  372.         self._post_clean()

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\forms\models.py" in _post_clean
  393.             self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\forms\models.py" in construct_instance
  65.             f.save_form_data(instance, cleaned_data[f.name])

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\db\models\fields\__init__.py" in save_form_data
  833.         setattr(instance, self.name, data)

File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.10.5-py3.6.egg\django\db\models\fields\related_descriptors.py" in __set__
  211.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /Catalogue/
Exception Value: Cannot assign "'14'": "Cart.Product_ID" must be a "Product" instance.



Share this traceback on a public website
Request information

USER
Wildcard91
GET
No GET data
POST
Variable    Value
csrfmiddlewaretoken 
'o9dVi0XNWtAA5ZV5dsz4pJ8gKRrC3jtjpC8XKVPaqnyCmzi632zmNN8z0jeoYseQ'
Product_ID  
'14'
HowMany 
'1'
DateSubmit  
'2017-03-21 15:36:00.819886'
initial-DateSubmit  
'2017-03-21 15:36:00.819886'
Cart14  
'Add to Cart'
FILES
No FILES data
COOKIES
Variable    Value
sessionid   
'5sctxyy2mfier9zptze2t5te96n4zvod'
csrftoken   
'jP6kYDKo7hGEMxLq5Dyuq5QeNB30SPTEki1mqyCLBbEG378rVdyMO9Qx33QMNYEb'
META
Variable    Value
ALLUSERSPROFILE 
'C:\\ProgramData'
APPDATA 
'C:\\Users\\User\\AppData\\Roaming'
CLASSPATH   
'.;C:\\Program Files (x86)\\QuickTime\\QTSystem\\QTJava.zip'
COMMONPROGRAMFILES  
'C:\\Program Files\\Common Files'
COMMONPROGRAMFILES(X86) 
'C:\\Program Files (x86)\\Common Files'
COMMONPROGRAMW6432  
'C:\\Program Files\\Common Files'
COMPUTERNAME    
'USER-PC'
COMSPEC 
'C:\\Windows\\system32\\cmd.exe'
CONTENT_LENGTH  
'766'
CONTENT_TYPE    
'multipart/form-data; boundary=----WebKitFormBoundaryuDZj0ni1h91jG0yg'
CSRF_COOKIE 
'jP6kYDKo7hGEMxLq5Dyuq5QeNB30SPTEki1mqyCLBbEG378rVdyMO9Qx33QMNYEb'
DJANGO_SETTINGS_MODULE  
'Wildcard91.settings'
DNX_HOME    
'%USERPROFILE%\\.dnx'
FP_NO_HOST_CHECK    
'NO'
GATEWAY_INTERFACE   
'CGI/1.1'
HOMEDRIVE   
'C:'
HOMEPATH    
'\\Users\\User'
HTTP_ACCEPT 
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
HTTP_ACCEPT_ENCODING    
'gzip, deflate, br'
HTTP_ACCEPT_LANGUAGE    
'en-US,en;q=0.8'
HTTP_CACHE_CONTROL  
'max-age=0'
HTTP_CONNECTION 
'keep-alive'
HTTP_COOKIE 
('sessionid=5sctxyy2mfier9zptze2t5te96n4zvod; '
 'csrftoken=jP6kYDKo7hGEMxLq5Dyuq5QeNB30SPTEki1mqyCLBbEG378rVdyMO9Qx33QMNYEb')
HTTP_HOST   
'127.0.0.1:8000'
HTTP_ORIGIN 
'http://127.0.0.1:8000'
HTTP_REFERER    
'http://127.0.0.1:8000/Catalogue/'
HTTP_UPGRADE_INSECURE_REQUESTS  
'1'
HTTP_USER_AGENT 
('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like '
 'Gecko) Chrome/57.0.2987.98 Safari/537.36')
LOCALAPPDATA    
'C:\\Users\\User\\AppData\\Local'
LOGONSERVER 
'\\\\USER-PC'
NUMBER_OF_PROCESSORS    
'4'
OS  
'Windows_NT'
PATH    
('C:\\Program Files (x86)\\Intel\\iCLS Client\\;C:\\Program Files\\Intel\\iCLS '
 'Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program '
 'Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program '
 'Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files '
 '(x86)\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program '
 'Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files '
 '(x86)\\AMD\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\NVIDIA '
 'Corporation\\PhysX\\Common;C:\\Program Files '
 '(x86)\\QuickTime\\QTSystem\\;C:\\Program Files (x86)\\Microsoft SQL '
 'Server\\100\\Tools\\Binn\\;C:\\Program Files\\Microsoft SQL '
 'Server\\100\\Tools\\Binn\\;C:\\Program Files\\Microsoft SQL '
 'Server\\100\\DTS\\Binn\\;C:\\Windows\\system32\\config\\systemprofile\\.dnx\\bin;C:\\Program '
 'Files\\Microsoft DNX\\Dnvm\\;C:\\Program Files\\Microsoft SQL '
 'Server\\130\\Tools\\Binn\\;C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Program '
 'Files\\Git\\cmd\\;C:\\Program Files\\Git\\cmd\\;C:\\Program '
 'Files\\Git\\bin\\;C:\\Program '
 'Files\\nodejs\\;C:\\Users\\User\\.dnx\\bin;C:\\Users\\User\\AppData\\Roaming\\npm')
PATHEXT 
'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY'
PATH_INFO   
'/Catalogue/'
PROCESSOR_ARCHITECTURE  
'AMD64'
PROCESSOR_IDENTIFIER    
'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel'
PROCESSOR_LEVEL 
'6'
PROCESSOR_REVISION  
'3c03'
PROGRAMDATA 
'C:\\ProgramData'
PROGRAMFILES    
'C:\\Program Files'
PROGRAMFILES(X86)   
'C:\\Program Files (x86)'
PROGRAMW6432    
'C:\\Program Files'
PROMPT  
'$P$G'
PSMODULEPATH    
'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\'
PUBLIC  
'C:\\Users\\Public'
QTJAVA  
'C:\\Program Files (x86)\\QuickTime\\QTSystem\\QTJava.zip'
QUERY_STRING    
''
REMOTE_ADDR 
'127.0.0.1'
REMOTE_HOST 
''
REQUEST_METHOD  
'POST'
RUN_MAIN    
'true'
SCRIPT_NAME 
''
SERVER_NAME 
'User-PC'
SERVER_PORT 
'8000'
SERVER_PROTOCOL 
'HTTP/1.1'
SERVER_SOFTWARE 
'WSGIServer/0.2'
SESSIONNAME 
'Console'
SYSTEMDRIVE 
'C:'
SYSTEMROOT  
'C:\\Windows'
TEMP    
'C:\\Users\\User\\AppData\\Local\\Temp'
TMP 
'C:\\Users\\User\\AppData\\Local\\Temp'
USERDOMAIN  
'User-PC'
USERNAME    
'User'
USERPROFILE 
'C:\\Users\\User'
VS100COMNTOOLS  
'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\Tools\\'
VS140COMNTOOLS  
'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\'
WINDIR  
'C:\\Windows'
WINDOWS_TRACING_FLAGS   
'3'
WINDOWS_TRACING_LOGFILE 
'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log'
wsgi.errors 
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>
wsgi.file_wrapper   
''
wsgi.input  
<_io.BufferedReader name=800>
wsgi.multiprocess   
False
wsgi.multithread    
True
wsgi.run_once   
False
wsgi.url_scheme 
'http'
wsgi.version    
(1, 0)
Settings
Using settings module Wildcard91.settings
Setting Value
ABSOLUTE_URL_OVERRIDES  
{}
ADMINS  
[]
ALLOWED_HOSTS   
[]
APPEND_SLASH    
True
AUTHENTICATION_BACKENDS 
['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS    
'********************'
AUTH_USER_MODEL 
'auth.User'
BASE_DIR    
'C:\\Users\\User\\PycharmProjects\\Wildcard91\\Wildcard91'
CACHES  
{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS  
'default'
CACHE_MIDDLEWARE_KEY_PREFIX 
'********************'
CACHE_MIDDLEWARE_SECONDS    
600
CSRF_COOKIE_AGE 
31449600
CSRF_COOKIE_DOMAIN  
None
CSRF_COOKIE_HTTPONLY    
False
CSRF_COOKIE_NAME    
'csrftoken'
CSRF_COOKIE_PATH    
'/'
CSRF_COOKIE_SECURE  
False
CSRF_FAILURE_VIEW   
'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME    
'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS    
[]
DATABASES   
{'default': {'ATOMIC_REQUESTS': False,
             'AUTOCOMMIT': True,
             'CONN_MAX_AGE': 0,
             'ENGINE': 'django.db.backends.postgresql_psycopg2',
             'HOST': '',
             'NAME': 'Wildcard91Db',
             'OPTIONS': {},
             'PASSWORD': '********************',
             'PORT': '',
             'TEST': {'CHARSET': None,
                      'COLLATION': None,
                      'MIRROR': None,
                      'NAME': None},
             'TIME_ZONE': None,
             'USER': 'postgres'}}
DATABASE_ROUTERS    
[]
DATA_UPLOAD_MAX_MEMORY_SIZE 
2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS   
1000
DATETIME_FORMAT 
'N j, Y, P'
DATETIME_INPUT_FORMATS  
['%Y-%m-%d %H:%M:%S',
 '%Y-%m-%d %H:%M:%S.%f',
 '%Y-%m-%d %H:%M',
 '%Y-%m-%d',
 '%m/%d/%Y %H:%M:%S',
 '%m/%d/%Y %H:%M:%S.%f',
 '%m/%d/%Y %H:%M',
 '%m/%d/%Y',
 '%m/%d/%y %H:%M:%S',
 '%m/%d/%y %H:%M:%S.%f',
 '%m/%d/%y %H:%M',
 '%m/%d/%y']
DATE_FORMAT 
'N j, Y'
DATE_INPUT_FORMATS  
['%Y-%m-%d',
 '%m/%d/%Y',
 '%m/%d/%y',
 '%b %d %Y',
 '%b %d, %Y',
 '%d %b %Y',
 '%d %b, %Y',
 '%B %d %Y',
 '%B %d, %Y',
 '%d %B %Y',
 '%d %B, %Y']
DEBUG   
True
DEBUG_PROPAGATE_EXCEPTIONS  
False
DECIMAL_SEPARATOR   
'.'
DEFAULT_CHARSET 
'utf-8'
DEFAULT_CONTENT_TYPE    
'text/html'
DEFAULT_EXCEPTION_REPORTER_FILTER   
'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE    
'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL  
'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE    
''
DEFAULT_TABLESPACE  
''
DISALLOWED_USER_AGENTS  
[]
EMAIL_BACKEND   
'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST  
'localhost'
EMAIL_HOST_PASSWORD 
'********************'
EMAIL_HOST_USER 
''
EMAIL_PORT  
25
EMAIL_SSL_CERTFILE  
None
EMAIL_SSL_KEYFILE   
'********************'
EMAIL_SUBJECT_PREFIX    
'[Django] '
EMAIL_TIMEOUT   
None
EMAIL_USE_SSL   
False
EMAIL_USE_TLS   
False
FILE_CHARSET    
'utf-8'
FILE_UPLOAD_DIRECTORY_PERMISSIONS   
None
FILE_UPLOAD_HANDLERS    
['django.core.files.uploadhandler.MemoryFileUploadHandler',
 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE 
2621440
FILE_UPLOAD_PERMISSIONS 
None
FILE_UPLOAD_TEMP_DIR    
None
FIRST_DAY_OF_WEEK   
0
FIXTURE_DIRS    
[]
FORCE_SCRIPT_NAME   
None
FORMAT_MODULE_PATH  
None
IGNORABLE_404_URLS  
[]
INSTALLED_APPS  
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.postgres',
 'Shop.apps.ShopConfig']
INTERNAL_IPS    
[]
LANGUAGES   
[('af', 'Afrikaans'),
 ('ar', 'Arabic'),
 ('ast', 'Asturian'),
 ('az', 'Azerbaijani'),
 ('bg', 'Bulgarian'),
 ('be', 'Belarusian'),
 ('bn', 'Bengali'),
 ('br', 'Breton'),
 ('bs', 'Bosnian'),
 ('ca', 'Catalan'),
 ('cs', 'Czech'),
 ('cy', 'Welsh'),
 ('da', 'Danish'),
 ('de', 'German'),
 ('dsb', 'Lower Sorbian'),
 ('el', 'Greek'),
 ('en', 'English'),
 ('en-au', 'Australian English'),
 ('en-gb', 'British English'),
 ('eo', 'Esperanto'),
 ('es', 'Spanish'),
 ('es-ar', 'Argentinian Spanish'),
 ('es-co', 'Colombian Spanish'),
 ('es-mx', 'Mexican Spanish'),
 ('es-ni', 'Nicaraguan Spanish'),
 ('es-ve', 'Venezuelan Spanish'),
 ('et', 'Estonian'),
 ('eu', 'Basque'),
 ('fa', 'Persian'),
 ('fi', 'Finnish'),
 ('fr', 'French'),
 ('fy', 'Frisian'),
 ('ga', 'Irish'),
 ('gd', 'Scottish Gaelic'),
 ('gl', 'Galician'),
 ('he', 'Hebrew'),
 ('hi', 'Hindi'),
 ('hr', 'Croatian'),
 ('hsb', 'Upper Sorbian'),
 ('hu', 'Hungarian'),
 ('ia', 'Interlingua'),
 ('id', 'Indonesian'),
 ('io', 'Ido'),
 ('is', 'Icelandic'),
 ('it', 'Italian'),
 ('ja', 'Japanese'),
 ('ka', 'Georgian'),
 ('kk', 'Kazakh'),
 ('km', 'Khmer'),
 ('kn', 'Kannada'),
 ('ko', 'Korean'),
 ('lb', 'Luxembourgish'),
 ('lt', 'Lithuanian'),
 ('lv', 'Latvian'),
 ('mk', 'Macedonian'),
 ('ml', 'Malayalam'),
 ('mn', 'Mongolian'),
 ('mr', 'Marathi'),
 ('my', 'Burmese'),
 ('nb', 'Norwegian Bokmål'),
 ('ne', 'Nepali'),
 ('nl', 'Dutch'),
 ('nn', 'Norwegian Nynorsk'),
 ('os', 'Ossetic'),
 ('pa', 'Punjabi'),
 ('pl', 'Polish'),
 ('pt', 'Portuguese'),
 ('pt-br', 'Brazilian Portuguese'),
 ('ro', 'Romanian'),
 ('ru', 'Russian'),
 ('sk', 'Slovak'),
 ('sl', 'Slovenian'),
 ('sq', 'Albanian'),
 ('sr', 'Serbian'),
 ('sr-latn', 'Serbian Latin'),
 ('sv', 'Swedish'),
 ('sw', 'Swahili'),
 ('ta', 'Tamil'),
 ('te', 'Telugu'),
 ('th', 'Thai'),
 ('tr', 'Turkish'),
 ('tt', 'Tatar'),
 ('udm', 'Udmurt'),
 ('uk', 'Ukrainian'),
 ('ur', 'Urdu'),
 ('vi', 'Vietnamese'),
 ('zh-hans', 'Simplified Chinese'),
 ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI  
['he', 'ar', 'fa', 'ur']
LANGUAGE_CODE   
'en-us'
LANGUAGE_COOKIE_AGE 
None
LANGUAGE_COOKIE_DOMAIN  
None
LANGUAGE_COOKIE_NAME    
'django_language'
LANGUAGE_COOKIE_PATH    
'/'
LOCALE_PATHS    
[]
LOGGING 
{}
LOGGING_CONFIG  
'logging.config.dictConfig'
LOGIN_REDIRECT_URL  
'/accounts/profile/'
LOGIN_URL   
'/accounts/login/'
LOGOUT_REDIRECT_URL 
None
MANAGERS    
[]
MEDIA_ROOT  
'C:\\Users\\User\\PycharmProjects\\Wildcard91\\Wildcard91\\media'
MEDIA_URL   
'/media/'
MESSAGE_STORAGE 
'django.contrib.messages.storage.fallback.FallbackStorage'
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']
MIDDLEWARE_CLASSES  
['django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware']
MIGRATION_MODULES   
{}
MONTH_DAY_FORMAT    
'F j'
NUMBER_GROUPING 
0
PASSWORD_HASHERS    
'********************'
PASSWORD_RESET_TIMEOUT_DAYS 
'********************'
PREPEND_WWW 
False
ROOT_URLCONF    
'Wildcard91.urls'
SECRET_KEY  
'********************'
SECURE_BROWSER_XSS_FILTER   
False
SECURE_CONTENT_TYPE_NOSNIFF 
False
SECURE_HSTS_INCLUDE_SUBDOMAINS  
False
SECURE_HSTS_SECONDS 
0
SECURE_PROXY_SSL_HEADER 
None
SECURE_REDIRECT_EXEMPT  
[]
SECURE_SSL_HOST 
None
SECURE_SSL_REDIRECT 
False
SERVER_EMAIL    
'root@localhost'
SESSION_CACHE_ALIAS 
'default'
SESSION_COOKIE_AGE  
1209600
SESSION_COOKIE_DOMAIN   
None
SESSION_COOKIE_HTTPONLY 
True
SESSION_COOKIE_NAME 
'sessionid'
SESSION_COOKIE_PATH 
'/'
SESSION_COOKIE_SECURE   
False
SESSION_ENGINE  
'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE 
False
SESSION_FILE_PATH   
None
SESSION_SAVE_EVERY_REQUEST  
False
SESSION_SERIALIZER  
'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE 
'Wildcard91.settings'
SHORT_DATETIME_FORMAT   
'm/d/Y P'
SHORT_DATE_FORMAT   
'm/d/Y'
SIGNING_BACKEND 
'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS  
[]
STATICFILES_DIRS    
[]
STATICFILES_FINDERS 
['django.contrib.staticfiles.finders.FileSystemFinder',
 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE 
'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT 
None
STATIC_URL  
'/static/'
TEMPLATES   
[{'APP_DIRS': True,
  'BACKEND': 'django.template.backends.django.DjangoTemplates',
  'DIRS': [],
  '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']}}]
TEST_NON_SERIALIZED_APPS    
[]
TEST_RUNNER 
'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR  
','
TIME_FORMAT 
'P'
TIME_INPUT_FORMATS  
['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE   
'UTC'
USE_ETAGS   
False
USE_I18N    
True
USE_L10N    
True
USE_THOUSAND_SEPARATOR  
False
USE_TZ  
True
USE_X_FORWARDED_HOST    
False
USE_X_FORWARDED_PORT    
False
WSGI_APPLICATION    
'Wildcard91.wsgi.application'
X_FRAME_OPTIONS 
'SAMEORIGIN'
YEAR_MONTH_FORMAT   
'F Y'
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code.

5 个答案:

答案 0 :(得分:1)

发现问题,猜测在问题

中不包括forms.py是我的错

错误的一个

class TempCart(forms.ModelForm):
    Product_ID = forms.CharField(max_length=80, label="Product ID")
    HowMany = forms.IntegerField(label='HowMany')
    DateSubmit = forms.DateTimeInput()
    class Meta:
        model = Cart
        fields = ["Product_ID","HowMany","DateSubmit",]

问题在于字段

解决问题所需的只是删除“Product_ID”

fields = ["HowMany","DateSubmit",]

谢谢大家的帮助

干杯

但如果问的不是太多,任何人都可以解释为什么会这样吗? 为什么django会对字段中的“Product_ID”进行decilne?

答案 1 :(得分:0)

开始修复这个小小的语法错误:
VarProductId = Product.objecrs.get(PId =“Product_ID”)* Product.objects.get

答案 2 :(得分:0)

“无法指定”15“:”Cart.Product_ID“必须是”产品“实例。”

上面表示您尝试在Cart表中插入一行,Product_Id = 15.由于这是一个外键,Product_Id应该出现在class / table Product中。首先,请在Cart类中插入行之前插入Product中的值。这应该有用。

答案 3 :(得分:0)

除了我想提到的解决方案之外,还有一些:

  1. 我觉得你所启动的网络服务器还没有 刷新。尝试尽可能重新启动它。对我来说就是这样 问题在这里。
  2. 如果objecrs中存在拼写错误,您的异常陈述不是有效的经理而不是15。

  3. 在分配之前尝试记录/打印VarProductId的类型。

  4. 不要为所有变量添加Var前缀。这不是编写干净代码的方法。 python中的所有内容都是一个对象。所以没有 在为var添加前缀时有意义。

  5. 检查form.is_valid()后,始终使用form.cleaned_data来获取所需的数据。不是要求。

答案 4 :(得分:0)

除了objecrs错字之外,此代码应运行良好。

尝试删除.pyc个文件(特别是views.pyc)并重新启动开发服务器。