Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON decode error while sending post request during testing

I am trying to test my signup url. When I do the following it gives me an error.

tests.py

from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
class SignUpTest(TestCase):
    def test_createAccount(self):
        import pdb; pdb.set_trace()
        response = self.client.post('/signup/', {'username': 'test_username', 'password': 'test_password',"email":"[email protected]", "confirm_password":"test_password", "type_of_user":"1", "first_name":"john", "last_name":"doe"})
        print response
        self.assertIs(response, {"success":True})

It gives me the following error:

Internal Server Error: /signup/
Traceback (most recent call last):
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/akashtomar/Desktop/repo/onlinestore/portal/views.py", line 20, in signup
    data = json.loads(data)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 548, in post
    secure=secure, **extra)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 350, in post
    secure=secure, **extra)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 416, in generic
    return self.request(**r)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 501, in request
    six.reraise(*exc_info)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/akashtomar/Desktop/repo/onlinestore/portal/views.py", line 20, in signup
    data = json.loads(data)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

This is my urls.py

from django.conf.urls import url
from django.contrib import admin
from portal.views import *
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^signup/',signup,name='signup'),
    url(r'^addproduct/',addProduct,name='addproduct'),
    url(r'^logout/',logout,name='logout'),
    url(r'^login/',login,name='login'),
    url(r'^deleteproduct/',deleteProduct,name='deleteproduct'),
    url(r'^search/',search,name='search'),
    url(r'^update/',update,name='update'),
    url(r'^getproduct/',getProduct,name='getproduct'),
]

This is my views.py

@csrf_exempt
def signup(request):
    if request.method=='POST':
        data = request.body
        data = json.loads(data)
        username = data["username"]
        email = data["email"]
        password = data["password"]
        confirm_password = data["confirm_password"]
        first_name = data["first_name"]
        last_name = data["last_name"]
        type_of_user = data["type_of_user"]

        if password!=confirm_password:
            return JsonResponse({"success":False,"reason":"passwords don't match"})
        user = User(username=username,email=email,first_name=first_name,last_name=last_name)
        user.set_password(password)
        user.is_active=True
        try:
            user.save()
        except:
            return JsonResponse({"success":False,"reason":"user already exists"})

        user_a=authenticate(username=username,password=password)
        if user_a is not None:
            if user_a.is_active:
                log(request,user_a)
        else:
            return HttpResponse({"success":False,"reason":"internal db error"});

        access_token = str(uuid.uuid4().get_hex())
        try:
            # import pdb; pdb.set_trace()
            at = AccessToken(token_value=access_token)
            at.save()
            UserProfile(user=user,type_of_user=int(type_of_user),access_token=at).save()
        except:
            return JsonResponse({"success":False,"reason":"internal error"})
        return JsonResponse({"success":True,"access_token":access_token})

P.S I have tried using json.loads and json.dump and also tried using double quotes instead of single quotes. It is not working.

like image 585
Akash Tomar Avatar asked Nov 29 '25 11:11

Akash Tomar


1 Answers

The error is coming from signup view at line data = json.loads(data). In order to access the POST data you can simply access it by using request.POST:

data = request.POST

So remove these lines and replace with above line of code:

data = request.body
data = json.loads(data)

Or try (as figured out via discussion):

response = self.client.post('/signup/', json.dumps(my_data), content_type='application/json')
like image 147
Aamir Rind Avatar answered Dec 01 '25 01:12

Aamir Rind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!