0
votes

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'

1
add the full stacktraceyogesh10
added the stack traceback @YogeshMhaskuleANISH TIWARI

1 Answers

1
votes

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.