'str'对象没有属性'get'(Django)

时间:2014-11-20 22:59:40

标签: django string get

Ahoy Mateys!

这里有一个简单的模型,有一个简单的形式:

class Hardware(models.Model):
type_name = models.CharField(max_length=60)

def __unicode__(self):
    return self.type_name



class HardwareForm(ModelForm):
    class Meta:
        model = Hardware
        fields = ['type_name']

这是我的简单视图函数使用的:

def createHardware(request):
if request.method == 'POST':
    form = HardwareForm('request.POST')
    if form.is_valid():
        new_hardware = form.save()


        return render_to_response('administration/overview.html')
else:
    form = HardwareForm()

    return render_to_response('administration/create_hardware.html', {
                    'form': form, }, context_instance = RequestContext(request))

这是Traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/ticket/createHardware/

Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'ticket')
Installed Middleware:
('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:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args,  **callback_kwargs)
File "C:\Users\bachi_000\workspace\Help\src\ticket\views.py" in createHardware
  155.         if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  129.         return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  121.             self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  273.         self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  282.             value = field.widget.value_from_datadict(self.data, self.files,         self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in value_from_datadict
  207.         return data.get(name, None)

Exception Type: AttributeError at /ticket/createHardware/
Exception Value: 'str' object has no attribute 'get'

所以我得到了几个包含更多数据的表单,并且将空表单传递给html页面,填写并将它们POST回函数以获取表单中的数据是没有问题的。运行is_valid()并将数据传递给模型的新实例(以向其添加更多数据)

为什么我会遇到这个错误?

1 个答案:

答案 0 :(得分:1)

您需要将字典传递给HardwareForm,而不是字符串。

更改views.py

form = HardwareForm('request.POST')

为:

form = HardwareForm(request.POST)