'unicode' object has no attribute 'get

2019-06-22 16:04发布

问题:

I am writing django application and stuck with the error

'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:

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

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:

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

回答1:

return product_data

A Django view must return an HttpResponse object, not a string.

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

(The clickjacking 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 unicode string.)