2017-12-29 17 views
0

Django 1.11에서 기본 CRUD를 만들고 있습니다. DB에 값을 저장하는 동안이 오류가 발생합니다. 'breed'는이 함수에 대한 잘못된 키워드 인수입니다. DB에 유효한 필드가 있지만 'breed'를 제거하더라도 'name'과 같은 오류가 발생합니다./create에서의 TypeError

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^)[email protected]#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/' 

저는 장고를 처음 사용하는데 약간의 도움을 주시면 대단히 감사하겠습니다. 미리 감사드립니다!

답변

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('/') 

의 더 나은 우리가 명시 적으로 dog.save()``호출 할 필요가

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) 
+0

가 수행 모든 라인의 흔적에서,

이 제거 만들 사용하여 만들 수 있습니다? 왜냐하면'Dog.objects.create'는 객체를 생성하고 그것을 한 번에 저장하기 때문입니다. –

+0

이름이 첫 번째 경우에만 코드를 디버깅하도록 명령을 변경했지만 작동하지 않았습니다. 데프 (요청) 작성 :/ '유형'을 만드는 것은이 기능 –

+0

에 대한 잘못된 키워드 인수가 그렇습니다 만 – Exprator