0

I'm using django 1.11 and i'm getting a tough time in storing a Json response.Here's my views.py code

views.py

    # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import addinfomodels
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.core import serializers
import json
# Create your views here.
def addinfo(request):
    batch_year = [2016, 2017, 2018]
    dept = ['AERO', 'BME', 'CIVIL', 'CSE', 'ECE', 'EEE', 'E&I', 'MECH']
    type = ['onecredit', 'core', 'professional', 'openelective']
    return render(request, "cbcsportal/addinfo.html", {'type': type, 'batch': batch_year, 'dept': dept})

def rollvalue(request):
    return request.POST.get('rollno')
# d ={}
def jsonvalue(request):
    d = {"courses":[{"choices": [request.POST.get('choices00') ,request.POST.get('choices10')], "code": request.POST.get('code0'), "name": request.POST.get('name10')}]}

    ds = serializers.serialize('json', d)
    print ds
    return JsonResponse(ds, content_type="application/json", safe=False)


def posttodb(request):
    if request.method == "POST":
        data = addinfomodels()
        data.batch = request.POST.get('batch')
        data.dept = request.POST.get('dept')
        data.typeid = request.POST.get('typeid')
        data.type = request.POST.get('type')
        data.rollno = [rollvalue(request)]
        data.renderJSON = jsonvalue(request)
        data.starttime = request.POST.get('starttime0')
        data.endtime = request.POST.get('endtime0')
        data.save()
        return redirect('addinfo')

please help me i'm getting this error

'unicode' object has no attribute '_meta'

this is the traceback

Traceback:

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in posttodb 34. data.renderJSON = jsonvalue(request)

File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in jsonvalue 21. ds = serializers.serialize('json', d)

File "C:\Python27\lib\site-packages\django\core\serializers__init__.py" in serialize 129. s.serialize(queryset, **options)

File "C:\Python27\lib\site-packages\django\core\serializers\base.py" in serialize 84. concrete_model = obj._meta.concrete_model

Exception Type: AttributeError at /cbcs/posttodb Exception Value: 'unicode' object has no attribute '_meta'

ANISH TIWARI
  • 111
  • 1
  • 10

1 Answers1

1

Here:

d = {....}
ds = serializers.serialize('json', d)
#print ds
return JsonResponse(ds, content_type="application/json", safe=False)

You are passing a dict to serialize(). Django serializer are for serializing django's orm querysets (this is documented, and you could gave found out by reading the traceback).

The proper way to serialize a python dict to json is quite simply to use json.dumps(yourdict). BUT : in your case this is useless anyway, since JsonResponse expects a python dict as first argument and will take care of the serialization. Also you don't need to set the content type, it's already the default for JsonResponse. IOW, all you need is:

d = {....}
return JsonResponse(d, safe=False)

As a side note: here:

def posttodb(request):
    if request.method == "POST":
        data = addinfomodels()
        data.batch = request.POST.get('batch')
        data.dept = request.POST.get('dept')
        data.typeid = request.POST.get('typeid')
        data.type = request.POST.get('type')
        data.rollno = [rollvalue(request)]
        data.renderJSON = jsonvalue(request)
        data.starttime = request.POST.get('starttime0')
        data.endtime = request.POST.get('endtime0')
        data.save()

You're inserting data in your db that are unvalidated, unsanitized user inputs. DONT DO THAT !!! (unless you're happy to have your server hacked by the first script kiddie of course). Use Django forms (in this case ModelForm to take care of validation and sanitization.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thank you @bruno but i had already tried that but i was unable to save it to db .when doing so i get is not JSON serializable error – ANISH TIWARI Sep 21 '18 at 09:01
  • @ANISHTIWARI a traceback without the matching code is totally useless, but anwyay: bypassing validation and sanitization is NOT the correct solution. What you should do is to customozie your modelform's validation to correctly fill the form's `cleaned_data`. ALL THIS IS DOCUMENTED, so please read the FineManual and learn to use your tools properly. – bruno desthuilliers Sep 21 '18 at 09:12
  • actually this formed will be filled only by admin.There's no case of any hacking in this situation as of the environment this form will be filled.so no worries of hacking – ANISH TIWARI Sep 21 '18 at 09:18
  • the real problem is that my json response is not saving .i have updated the code n stack traceback @bruno – ANISH TIWARI Sep 21 '18 at 09:18
  • Why would you save a JsonResponse in a database anyway ??? This is beyond my imagination... Just save the json itself. And I already answered about why you had an exception in `jsonvalue()`. – bruno desthuilliers Sep 21 '18 at 09:22
  • "actually this formed will be filled only by admin.There's no case of any hacking in this situation" => I'm afraid you are overly confident, specially when your view doesn't check who is posting. But well, that's your problem if you get hacked. – bruno desthuilliers Sep 21 '18 at 09:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180503/discussion-between-anish-tiwari-and-bruno-desthuilliers). – ANISH TIWARI Sep 21 '18 at 09:25