[英]Django view AttributeError: 'str' object has no attribute 'get'
[英]AttributeError: 'unicode' object has no attribute 'get' - In Django Forms
我正在嘗試將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())
我嘗試了以下方法:
完整回溯:
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 Docs以正確調用AJAX:
https://docs.djangoproject.com/en/1.6/topics/class-based-views/generic-editing/#ajax-example
似乎一種解決方法是在視圖中構造表單。
我查看了十分零下的數百個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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.