Python “unicode”对象没有“get”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31817350/
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 10:35:22  来源:igfitidea点击:

'unicode' object has no attribute 'get'

pythondjangounicodedjango-ormattributeerror

提问by Jade

I am writing django application and stuck with the error

我正在编写 django 应用程序并遇到错误

'unicode' object has no attribute 'get'

I saw a lot of questions here but no one matches with mine issue.

我在这里看到了很多问题,但没有一个与我的问题相符。

The issue is with my method in views.py that should return JSON:

问题在于我在 views.py 中的方法应该返回 JSON:

def get_pattern(request, product_id):
    """
    Get JSON for needed pattern
    """
    data = Patterns.objects.get(related_module=product_id)
    product_data = serializers.serialize("json", [data, ])
    return product_data

My urls.py

我的网址.py

urlpatterns = [
url(r'^get_pattern(?P<product_id>[0-9]+)/$', views.get_pattern, name='get_pattern'),

]

]

I've tried everything. But when you go /get_pattern1 it returns:

我什么都试过了。但是当你去 /get_pattern1 它返回:

Request Method: GET
Request URL:    http://xxxxxxx:8000/xxxx/get_pattern1/
Django Version: 1.8.3
Exception Type: AttributeError
Exception Value:    
'unicode' object has no attribute 'get'
Exception Location: /home/xxxx/local/lib/python2.7/site-    packages/django/middleware/clickHymaning.py in process_response, line 31

采纳答案by bobince

return product_data

A Django view must return an HttpResponseobject, not a string.

Django 视图必须返回HttpResponse对象,而不是字符串。

bytes = product_data.encode('utf-8')
return django.http.HttpResponse(bytes, content_type='application/json')

(The clickHymaning middleware is raising an error because it is assuming the return value from the view is an HttpResponse and calling get()on it, but actually it's, erroneously, a unicodestring.)

(点击劫持中间件引发错误,因为它假设视图的返回值是一个 HttpResponse 并调用get()它,但实际上它错误地是一个unicode字符串。)