javascript - 属性错误: 'unicode' object has no attribute 'get' - In Django Forms

标签 javascript jquery ajax django

我正在尝试将 Django 表单与 Ajax 调用结合使用。

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

在我的 HTML 代码中(用户单击的页面,AJAX 使用 JavaScript 调用另一个 View ):

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 代码将调用此 View ,称为 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 =“我在浏览器中输入的一些文本”

最佳答案

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

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

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

尝试离开 Django 文档来正确调用 AJAX:

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

关于javascript - 属性错误: 'unicode' object has no attribute 'get' - In Django Forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27326638/

相关文章:

javascript - 与 AJAX 服务器对话时显示弹出 div

jquery - 如何在jsfiddle中加载和使用XML

javascript - 每次在用户脚本上触发 onChange onChange 时如何调用函数?

javascript - 使用 google-map api 仅使用确切位置填充文本框

javascript - Ember 计算属性是否旨在与异步代码一起使用/包含异步代码?

javascript - 使用 JavaScript 对 JSON 数据进行排序

javascript - 添加数据表中字段的总和

javascript - 如何在文本框中输入按键时生成 anchor 标记的点击事件

javascript - 查找 jQuery 中响应的所有属性的类型

php - 如何检测我使用 Bootstrap 数据表编辑过的单元格?