【问题标题】:AttributeError: 'unicode' object has no attribute 'get' - In Django FormsAttributeError:'unicode'对象没有属性'get' - 在Django Forms中
【发布时间】:2015-02-04 06:11:02
【问题描述】:

我正在尝试将 Django 表单与 Ajax 调用一起使用。

之前我只是使用了一个html表单,我可以通过request.POST['item']获取所有信息。但我一直在考虑验证器,如果我将普通的 html 表单转换为 Django 表单,我会受益。

在我的 HTML 代码中(用户点击的页面,AJAX 使用 javascript 调用另一个视图):

if not request.user.is_authenticated():
    #Tells the user to login if not authenticated 
    return redirect('/webapp/login.html')
else:
    #Get Logger 
    logger = logging.getLogger('views.logger.chartConfigure')
    logger_uuid = uuid.uuid4()
    logger_time = datetime.datetime.now()

    #Log the User
    logger.info("Request in editChart, User:" + str(request.user.username) + ", UUID:" + str(logger_uuid) + ", Time:" + str(logger_time))

    #Forms to use
    chartName = changeChartNameForm(auto_id=False)

    #Put Forms into a context
    context = {'chartNameForm': chartName}

    #Return the context
    return render(request, 'webapp/editChart.html', context)

使用的表单是 changeChartNameForm:

#Form for editing chart names
class changeChartNameForm(forms.Form):
    #Only one variable which is called chartName, with label set to ""
    #Since I don't want any labels. I have my own in HTML.
    chartName = forms.CharField(max_length=100, label="")
    #form-control is an extra class that is required by bootstrap 3, and the html id
    #of the form is called chartName
    chartName.widget.attrs['class'] = 'form-control'
    chartName.widget.attrs['id'] = 'chartName'

HTML 代码:

<div class="input-group">
    <span class="input-group-btn">
        <button class="btn btn-default" type="button" id="newChartName" >New Chart Name</button>
    </span>
    {{ chartNameForm }}
</div>

Javascript 代码:

$.ajax(
{
    type:"POST",
    url:"ajax_postColumnAction/",
    datatype: 'json',
    data:
    {
        'csrfmiddlewaretoken':csrftoken,
        'currentTabSelected':currentTabSelected,
        'currentColumnSelected':currentColumnSelected,
        'action':'changeName',
        'changeNameForm':$('#chartName').serialize()
    },
    success: function(response)
    {
        ...Some logic happens here
    }
}

基本上javascript代码会调用这个视图,叫做ajax_postColumnAction:

#Get the name form, and get the newName
changeNameForm = changeChartNameForm(request.POST['changeNameForm'])
newName = ""
if(changeNameForm.is_valid()):
    newName = changeNameForm.cleaned_data['chartName']

回报总是:

'unicode' 对象在以下行没有属性'get':if(changeNameForm.is_valid())

我尝试了以下方法:

  1. 使用 data=request.POST
  2. 使用 data=request.POST['changeNameForm']

完整追溯:

Traceback (most recent call last): 
File "C:\Users\Desktop\Dropbox (Personal)\Django\Dashboard_Web\WebApp\views.py", line 738, in ajax_postColumnAction if(changeNameForm.is_valid()): 
File "C:\Python27\lib\site-packages\django\forms\forms.py", line 129, in is_valid return self.is_bound and not bool(self.errors) 
File "C:\Python27\lib\site-packages\django\forms\forms.py", line 121, in errors self.full_clean() 
File "C:\Python27\lib\site-packages\django\forms\forms.py", line 273, in full_clean self._clean_fields() 
File "C:\Python27\lib\site-packages\django\forms\forms.py", line 282, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) 
File "C:\Python27\lib\site-packages\django\forms\widgets.py", line 207, in value_from_datadict return data.get(name, None) AttributeError: 'unicode' object has no attribute 'get'

编辑:

当我这样做时:

print request.POST['changeNameForm']

我得到 chartName = "我在浏览器中输入的一些文本"

【问题讨论】:

    标签: javascript jquery ajax django


    【解决方案1】:

    这部分错误说data是一个unicode字符串:

    return data.get(name, None) AttributeError: 'unicode' object has no attribute 'get'
    

    data 需要是一个对象。相反,它是一个字符串,并且字符串没有get() 方法,也没有name 属性,正如错误回溯所说的那样。

    尝试退出 Django Docs 以正确调用 AJAX:

    https://docs.djangoproject.com/en/1.6/topics/class-based-views/generic-editing/#ajax-example

    【讨论】:

    • 您好,感谢您的回复!我不明白的是request.POST返回了正常的帖子。在示例中:docs.djangoproject.com/en/dev/topics/forms form = NameForm(request.POST),效果很好。我的方式有什么不同?
    • 根据另一个stackoverflow帖子:stackoverflow.com/questions/7335780/…用户:user931920,表示“django代码可以像处理其他表单提交一样处理AJAX帖子”
    • 另外我使用的是基于函数的视图,而网页使用的是基于类的视图。
    【解决方案2】:

    似乎一种解决方法是在视图中构造表单。

    我查看了成百上千的 StackOverFlow 帖子和 Google 网站,但似乎都没有我的问题。

    方法是在获取 POST 数据时重新创建表单,因为表单使用字典作为构造函数。

    changeNameForm = changeChartNameForm({request.POST['changeNameForm'].split("=")[0]}):request.POST['changeNameForm'].split("=")[1]})
    

    我知道 request.POST['changeNameForm'] 返回一个字符串“chartName=someName”。我用“=”分割字符串,得到someName和chartName。因此,我会将 someName 放入字典中,键名为 chartName。

    {'chartName':'someName'}
    

    因此,表单使用发布数据重新创建,并最终通过 is_valid。

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 1970-01-01
      • 2020-04-01
      • 2020-11-07
      • 2021-07-04
      • 2012-05-11
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多