Python 获取'str'对象在Django中没有属性'get'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22788135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:40:59  来源:igfitidea点击:

Getting 'str' object has no attribute 'get' in Django

pythondjangodjango-viewsdjango-urls

提问by user3485393

views.py

视图.py

def generate_xml(request, number):
    caller_id = 'x-x-x-x'
    resp = twilio.twiml.Response()

    with resp.dial(callerId=caller_id) as r:
         if number and re.search('[\d\(\)\- \+]+$', number):
            r.number(number)
         else:
             r.client('test')
   return str(resp)

url.py

网址.py

url(r'^voice/(?P<number>\w+)$', 'django_calling.views.generate_xml', name='generating TwiML'),

Whenever I am requesting http://127.0.0.1:8000/voice/number?id=98getting following error:

每当我请求http://127.0.0.1:8000/voice/number?id=98收到以下错误时:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/voice/number?id=90
Django Version:     1.6.2
Exception Type:     AttributeError
Exception Value:    'str' object has no attribute 'get'

Exception Location:     /usr/local/lib/python2.7/dist-     

Full Traceback:

完整追溯:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/voice/number?id=90

Django Version: 1.6.2
Python Version: 2.7.5
Installed Applications:
 ('django.contrib.admin',
'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_calling',
'django_twilio',
'twilio')
 Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickHymaning.XFrameOptionsMiddleware')

I have just started to learn Django.

我刚刚开始学习Django

采纳答案by pygaur

You can not pass directly stras a django response. You must use

您不能直接str作为django response. 你必须使用

from django.http import HttpResponse

if you want to render string data as django view response. have a look here

如果要将字符串数据呈现为 django 视图响应。看看这里

return HttpResponse(resp)

回答by DavidM

Django views must always return an HttpResponseobject, so try wrapping that string in an HttpResponse:

Django 视图必须始终返回一个HttpResponse对象,因此请尝试将该字符串包装在 HttpResponse 中:

from django.http import HttpResponse
return HttpResponse(str(resp))

Additionally, the numbervariable in generate_xmlwill contain only the string 'number', not the GET parameter. To get that, you might use:

此外,number变量 ingenerate_xml将仅包含 string 'number',而不包含 GET 参数。为此,您可以使用:

request.GET.get('id')