I am getting this error...
Object of type 'Settings' is not JSON serializable
Here is my code
from django.conf import settings
import json
def get_settings(request):
responce = settings.__dict__
return HttpResponse(json.dumps(responce),content_type='application/json')
django.conf.settings is not Json serializable, thought you can go throught and create dict() then give it to HttpResponse. Hope it helps!
import json
from django.http import HttpResponse
from django.conf import settings
def get_settings(request):
context = {}
for setting in dir(settings):
if setting.isupper():
context[setting] = getattr(settings, setting)
return HttpResponse(json.dumps(context, indent=4), content_type="application/json")
Related
I have made an DjangoRestApi and giving user input using postman(POST method).but the error is
TypeError: Object of type 'JSONDecodeError' is not JSON serializable
it is showing in django server where i am going wrong please help Thanks
views.py
import spacy
from django.shortcuts import render,HttpResponse
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
import json
nlp = spacy.load('en_core_web_sm')
#api_view(["POST"])
def nounphrases(requestdata):
try:
text = json.loads(requestdata.body)
nounphrases = []
for word in (nlp((text))):
c = (word.lemma_)
nounphrases.append(c)
output = [{"nounphrases" : nounphrases }]
return JsonResponse(json.dumps(output))
except ValueError as e:
return Response(e,status.HTTP_400_BAD_REQUEST)
Sorry for my English. I have some data from another server, but I need to output this data like JSON.
if i print response in console:
{
'responseStatus': {
'status': [],
},
'modelYear': [
1981,
1982
]
}
but, if i return this response like HttpResponse i have an error
AttributeError: 'str' object has no attribute '_meta'
this my code:
data = serializers.serialize('json', response, ensure_ascii=False)
return HttpResponse(data, content_type="application/json")
UPD:
I tried with this:
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(response, safe=False)
but have error:
Object of type 'ModelYears' is not JSON serializable
UPD:
I did like this:
import json
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(json.loads(response))
but have error:
the JSON object must be str, bytes or bytearray, not 'ModelYears'
The Django docs says the following about the serializers framework:
Django’s serialization framework provides a mechanism for “translating” Django models into other formats.
The error indicates that your variable response is a string and not an Django model object. The string seems to be valid JSON so you could use JsonResponse:
import json
from django.http import JsonResponse
# View
return JsonResponse(json.loads(response))
Replace your code with following:
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(response)
Instead of serializing and sending it via httpresponse.
This works for python 3.6 and Django 2.0
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import requests
#login_required()
def get_some_items(request):
headers = {"Authorization": "Token uydsajbkdn3kh2gj32k432hjgv4h32bhmf"}
host = "https://site/api/items"
response = requests.get(host, headers=headers)
result = JsonResponse(response.json())
return HttpResponse(result, content_type='application/json')
I successfully implement with small cases. Then I started to work with bigger structure. And I got the error.
Error:
No file was submitted.
import tempfile
from unittest import skip
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from model_mommy import mommy
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
class CustomerFromExcelViewsetTest(APITestCase):
def setUp(self):
self.client = APIClient()
self.soken_staff = mommy.make(User, username='spearhead')
self.user = mommy.make(User, username='Justin')
settings.MEDIA_ROOT = tempfile.mkdtemp()
def test_upload_file(self):
"""Expect created_user, and updated_user correct set"""
file = File(open('./soken_web/apps/uploaded_files/complete-customer.xlsx', 'rb'))
uploaded_file = SimpleUploadedFile('new_excel.xlsx', file.read(), content_type='multipart/form-data')
data = {
file: uploaded_file,
}
self.client.force_authenticate(user=self.user)
response = self.client.post(reverse('api:customer_from_excel-list'), data, format='multipart')
response.render()
self.assertEqual(status.HTTP_201_CREATED, response.status_code)
Here they are the models, serializers, and viewsets
models.py https://gist.github.com/elcolie/52daf2bd144af82b348f7353656be434
serializers.py
https://gist.github.com/elcolie/7f097642c4a752e76044c6938c49e097
viewsets.py
https://gist.github.com/elcolie/34fa66632209f14624899d997919d3fb
After a day I could not figure out where is the that bug.
References:
DRF APITestCase not use `multipart` with other param
looks like you missed quotes in data dict. It should be:
data = {
'file': uploaded_file,
}
I am very new with django framework.
# Create your views here.
import urllib2
import json
import urllib
from .models import Apiclass
from django.shortcuts import render_to_response
from django.conf import settings as config
def home(request):
obj = Apiclass()
def postme(request):
url = config.API_PROTOCOL+config.API_DOMAIN+config.API_SECURE_USER_URL
# user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'username' : 'waheeda#auction.com',
'password' : '12345678'
}
# headers = { 'Content-Type' : "application/json" }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = json.loads(response.read())
return render_to_response("home.html",{'postme':the_page})
And ApiClass is under models/Apiclass.py
I tried many ways to import the model ApiClass
such as
- from app1.models import Apiclass
- from .models import Apiclass
but it still does not work it gave me the errors like this
TypeError at /api
'module' object is not callable
Apiclass.py
I just comment all the implementation when ever I can create object that everything should be good. Here is the Apiclass code
import urllib2
import urllib
import json
from django.conf import settings as config
# Create your models here.
class Apiclass:
api_domain = config.API_DOMAIN
Your should have class Apiclass inside models.py. Also I recommend you to import from full module path .i.e from YOUR_APP.models import Apiclass
If you want folder structure:
models/
__init__.py
and inside __init__.py you could have Apiclass and import as from YOUR_APP.models import Apiclass as well.
Also make sure it is subclassed from django.db.models.Model if it touches database in any way as recommended below.
You haven't subclassed your ApiClass model correctly. It should subclass django Model
from django.db import models
class ApiClass(models.Model):
pass
It's barfing because you are trying to call your class with this:
Apiclass()
but ApiClass doesn't currently have a call method.
Hi I'm siting with my custom storage system 1 day. And now when I'm trying import it it gives me this Error.
I put in file models.py
from FTPStorage import FTPStorage
import datetime
from django.db import models
fs=FTPStorage()
class Upload(models.Model):
"""Uploaded files."""
file = models.FileField(upload_to='uploads', store=fs)
timestamp = models.DateTimeField(default=datetime.datetime.now)
notes = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ['-timestamp',]
def __unicode__(self):
return u"%s" % (self.file)
#property
def size(self):
return filesizeformat(self.file.size)
here is my views.py:
from forms import UploadForm
from models import Upload
import ftplib
import os
import datetime
from django.forms import save_instance
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from FTPStorage import FTPStorage
from django.core.files.storage import Storage
def initial(request):
data = {
'form': UploadForm(),
}
return render_to_response('upload.html', data, RequestContext(request))
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload()
upload.timestamp = datetime.datetime.now()
save_instance(form, upload)
return HttpResponseRedirect(reverse('initial'))
and file custom storage system FTPStorage.py is in direectory app
I have this problem:
Request Method: GET
Request URL: http://localhost:2121/
Exception Type: ViewDoesNotExist
Exception Value:
Could not import app.views. Error was: cannot import name FTPStorage
Exception Location: C:\BitNami DjangoStack\apps\django\django\core\urlresolvers.py in _get_callback, line 134
Please help me. I confuse.
It seems to me that you need to update the PYTHONPATH for your runtime. Based on your error page I think you're using mod_python so try this setting in apache:
PythonPath "sys.path+['/mydir']"
Where /mydir is the full path to wherever the FTPStorage module resides.