/Error处的TypeError

时间:2017-12-29 05:24:12

标签: python django django-models

我在Django 1.11中制作基本的CRUD。 在将值保存到DB时,我收到此错误,'breed'是此函数的无效关键字参数。 虽然DB中有一个有效字段,但即使我删除'品种',我也会在'name'中出现相同的错误。

Environment:


Request Method: POST
Request URL: http://e0c0a02d057f4394aa9e52d4f67c7edb.vfs.cloud9.us-east-2.amazonaws.com/create

Django Version: 1.11
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'apps.dog_app']
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 "/usr/local/lib64/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/ec2-user/environment/dogs/apps/dog_app/views.py" in create
  14.     dog = Dog(breed=request.POST['breed'],name=request.POST['name'])

File "/usr/local/lib64/python2.7/site-packages/django/db/models/base.py" in __init__
  571.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /create
Exception Value: 'breed' is an invalid keyword argument for this function

Views.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from models import Dog
from django.shortcuts import render,redirect

# Create your views here.
def index(request):
    dogs=Dog.objects.all()
    context={ 'dogs': dogs}
    return render(request, 'dog_app/index.html', context)

def create(request):
    #print (request.POST['name'],request.POST['breed'])
    dog = Dog(breed=request.POST['breed'],name=request.POST['name'])
    dog.save()
    return redirect('/')

的index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>

      <form action="/create" method="post">
          {% csrf_token %}
          <label for="name">Name: <input type="text" name="name"  id="name"/></label>
          <label for="breed">Breed: <input type="text"  id="breed" name="breed"/></label>
          <input type="Submit" value="Create"/>
      </form>
      <table border="1">
          <thead>
              <tr>
              <th>Dog name</th>
              <th>Breed</th>
              <th>created_at</th>
              <th>updated_at</th>
              <th>Actionsa</th>
              </tr>
          </thead>
          <tbody>
              {% for dog in dogs %}
              <tr>
              <td>{{ dog.name }}</td>
              <td>{{ dog.breed }}</td>
              <td>{{ dog.created_at }}</td>
              <td>{{ dog.updated_at }}</td>
              <td><a href="/edit/{{ dog.id }}">Edit</a></td>
              <td><a href="/delete/{{ dog.id }}">Delete</a></td>
              </tr>
              {% endfor %}

          </tbody>
      </table>
    </body>
</html>

Models.py:

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Dog(models.Model):
    name=models.CharField(max_length=45),
    breed=models.CharField(max_length=45),
    created_at=models.DateTimeField(auto_now_add = True),
    updated_at=models.DateTimeField(auto_now= True)

Settings.py:

"""
Django settings for dogs project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&swd40kc6*k73v4^)96ig11c@#9^_wp&%=dcn)8p+6gipyxu^l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [u'e0c0a02d057f4394aa9e52d4f67c7edb.vfs.cloud9.us-east-2.amazonaws.com',]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.dog_app',
]

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 = 'dogs.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'dogs.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/

STATIC_URL = '/static/'

我是Django的新手,一点点的帮助将受到高度赞赏:) 提前谢谢!

1 个答案:

答案 0 :(得分:0)

def create(request):
    #print (request.POST['name'],request.POST['breed'])
    dog = Dog.objects.create(breed=request.POST['breed'],name=request.POST['name'])
    dog.save()
    return redirect('/')

使用create

创建更好

从每行的踪迹中删除

class Dog(models.Model):
    name=models.CharField(max_length=45)
    breed=models.CharField(max_length=45)
    created_at=models.DateTimeField(auto_now_add = True)
    updated_at=models.DateTimeField(auto_now= True)