'str'对象没有属性'get'

时间:2016-10-28 15:25:00

标签: python django modelform

我试图通过覆盖 init 在模型中设置字段的选择 但是我得到了这个错误

 'str' object has no attribute 'get'

forms.py

class carOwnerForm(forms.ModelForm):
first_name = forms.charfield()
last_name = forms.charfield()

def __init__(self, a,b,c):
    super(carOwnerForm,self).__init(a,b,c)
    self.fields['ownership_Type'].choices = [(a,'c'),(b,'b'),(c,'x')]

class Meta:
    model = CarOwner
    fields = ['ownership_type','CarModel']

查看

def CarOwnerSearch(request):
if request.user.is_authenticated():
    form = carOwnerForm('B','None','C')
    return render (request,'carmanager/CarOwnerSearch.html', {'form': form})
html中的

错误

    Request Method:     GET
Request URL:    http://127.0.0.1:8000/parcelmanager/CrownLandsSearch/
Django Version:     1.8
Exception Type:     AttributeError
Exception Value:    

'list' object has no attribute 'get'

Exception Location:     C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 223





      Traceback:
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Sites\laisy\carmanager\views.py" in CrownLandsSearch
  811.         return render (request,'carmanager/CrownLandsSearch.html', {'form': form})
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\shortcuts.py" in render
  67.             template_name, context, request=request, using=using)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\loader.py" in render_to_string
  99.         return template.render(context, request)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\backends\django.py" in render
  74.         return self.template.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render
  209.                     return self._render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in _render
  201.         return self.nodelist.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render
  903.                 bit = self.render_node(node, context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\loader_tags.py" in render
  135.         return compiled_parent._render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in _render
  201.         return self.nodelist.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render
  903.                 bit = self.render_node(node, context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\loader_tags.py" in render
  65.                 result = block.nodelist.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render
  903.                 bit = self.render_node(node, context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render
  89.             output = self.filter_expression.resolve(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in resolve
  647.                 obj = self.var.resolve(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in resolve
  787.             value = self._resolve_lookup(context)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in _resolve_lookup
  847.                             current = current()
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in as_p
  302.             errors_on_separate_row=True)
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in _html_output
  203.         top_errors = self.non_field_errors()  # Errors that should be displayed above all fields.
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in non_field_errors
  310.         return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in errors
  176.             self.full_clean()
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in full_clean
  392.         self._clean_fields()
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\forms.py" in _clean_fields
  401.             value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\widgets.py" in value_from_datadict
  223.         return data.get(name, None)

Exception Type: AttributeError at /parcelmanager/carOwnerSearch/
Exception Value: 'str' object has no attribute 'get'

2 个答案:

答案 0 :(得分:3)

你会这样做来解决这个问题......

你的form.py

class CarOwnerForm(forms.ModelForm):
    first_name = forms.charfield()
    last_name = forms.charfield()

    class Meta:
        model = CarOwner
        fields = ['ownership_type','CarModel']

    def __init__(self, *args, **kwargs):
        _choices_list = kwargs.pop('_choices', None)
        super(CarOwnerForm, self).__init__(*args, **kwargs)
        if _choices_list is not None:
            # this only works if 'ownership_type' is a CharField... and it will be your error
            self.fields['ownership_type'].choice = _choices_list  # I don't remeber if the attribute is 'choice' or 'choices'
            # if 'ownership_type' is a RelationField, you must set queryset and not a list of strings

和你的views.py

...
def car_owner_search(request):
    """Doctype for view"""
    if request.user.is_authenticated():
        _CHOICE_LIST = ['B', 'None', 'C']
        if request.method == 'POST':
             form = CarOwnerForm(data=request.POST, _choices=_CHOICE_LIST)

             if form.is_valid():
                your_model = form.save(commit=False)
                your_model.first_name = form.cleaned_data['first_name']
                your_model.save()
        else:
            form = CarOwnerForm(_choices=_CHOICE_LIST)
        return render (request,'carmanager/CarOwnerSearch.html', {'form': form})
    return HttpRedirect('/login/') # or other HttpResponse

答案 1 :(得分:1)

这里确实存在很多错误。

首先,modelforms期望某个界面。他们接受POST,任何初始数据和模型实例。但是你已经覆盖了这一点,所以他们只接受 let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) let firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView) let secondFrame = CGRect(x: 20, y: 30, width: 50, height: 50) let secondView = UIView(frame: secondFrame) secondView.backgroundColor = UIColor.greenColor() view.addSubview(secondView) ,无论那是什么;你不仅摧毁了班级做它需要做的事情的能力,你还把这些论点传递给了那些不期望它们的超类。

其次,您需要更加注意您的属性。表单没有a, b, c属性,他们有field;一个选择字段没有fields属性,它有choice;对于ID和显示值,选择需要是可迭代的迭代,而不是单个可迭代。