AttributeError的:“UNI code'对象有没有属性'得到' - 在Django的形式 [英] AttributeError: 'unicode' object has no attribute 'get' - In Django Forms

查看:241
本文介绍了AttributeError的:“UNI code'对象有没有属性'得到' - 在Django的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Django的形式与Ajax调用。

I'm trying to use Django Forms with Ajax Calls.

previously我只是用一个HTML表单,我可以通过request.POST ['项目']获得所有信息。但是,我一直在想验证的,如果我换普通的HTML表单到Django的形式我将受益。

Previously I just used a html form that I could get all the information through request.POST['item']. But I've been thinking about validators, and I would benefit if I switched normal html forms into Django forms.

在我的HTML code(用户点击,和AJAX调用另一个观点支持JavaScript的页面):

In my HTML code (the page where the user clicks, and a AJAX calls another view with 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:

The Forms that are used is a 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 code:

HTML Code:

<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的code:

The Javascript code:

$.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的code将调用这一观点,被称为ajax_postColumnAction:

basically the javascript code will call this view, called 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']

返回的永远是:

The return is always:

UNI code'对象没有属性'得到'在下面一行:如果(changeNameForm.is_valid())

'unicode' object does not have the attribute 'get' at the following line: if(changeNameForm.is_valid())

我已经试过如下:

  1. 在使用数据= request.POST
  2. 在使用数据= 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 =一些文字我输入浏览器的

I get chartName = "some text I typed in the browser"

推荐答案

看来,一个解决方法是在视图构建形式。

It seems that a workaround is to construct the form in the view.

我看着十分之一和数百个计算器的职位和谷歌的网站,不似乎有我的问题。

I've looked at tenths and hundreds of StackOverFlow posts and Google websites, and non seem to have my problem.

该方法是重新创建窗体时,你得到的POST数据,因为形式使用字典作为一个构造函数。

The method is to recreate the form when you get the POST data, since a form uses a dictionary as a constructor.

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

我知道,request.POST ['changeNameForm']返回一个字符串chartName = someName。我分割字符串为=,我会得到someName和chartName。因此,我会把someName成一个字典,用所谓chartName的关键。

I know that request.POST['changeNameForm'] returns a string "chartName=someName". I split the string with "=", and I would get someName, and chartName. Hence I would put someName into a dictionary, with the key called chartName.

{'chartName':'someName'}

因此​​,形式与重建后的数据,最后通过is_valid。

Hence the form is recreated with the post data and finally passes is_valid.

这篇关于AttributeError的:“UNI code'对象有没有属性'得到' - 在Django的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆