“Unicode”对象没有“get”属性。

6
我正在编写 Django 应用程序,卡在了错误上。
'unicode' object has no attribute 'get'

我看到了很多问题,但没有一个与我的问题相匹配。
我的问题是在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

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

我已经尝试了所有的方法。但是当你执行 /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/clickjacking.py in process_response, line 31

你有任何中间件吗?如果有,请展示它。 - Gocht
1
我猜测 Patterns.objects.get 并不是你的问题所在(假设你确实有一个 Patterns 模型类,并且没有对 objects 属性进行任何有趣的操作)... 你在控制台上看到任何错误消息了吗(如果你正在使用 Apache 进行主机托管,则可以查看 Apache 日志)? - Joran Beasley
不,我没有。这几乎是原始的Django安装。 - Jade
你的调试模式设置为true了吗? - Joran Beasley
@JoranBeasley 当我尝试通过浏览器访问它时,它会向前端返回500错误,并出现attributeError。 - Jade
你的某个地方有一个名为 process_response 的方法,请在内部查看。 - Gocht
1个回答

11
return product_data

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

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

点击劫持中间件出现错误,因为它假定视图函数的返回值是一个HttpResponse对象,并在其上调用get()方法,但实际上这个返回值错误地是一个unicode字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接