I am trying to make a json array in django but I am getting error -
In order to allow non-dict objects to be serialized set the safe parameter to False
and my views.py -
def wall_copy(request):
if True:
posts = user_post.objects.order_by('id')[:20].reverse()
return JsonResponse(posts)
Basically user_post is a model a posts is the object of top 20 saved data. I want to send a json array but I am unable to convert posts into a json array. I also tried serializers but it didnt helped.
I am stuck help me please.
Thanks in advance.
Would this solve your problem?
from django.core import serializers
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
posts_serialized = serializers.serialize('json', posts)
return JsonResponse(posts_serialized, safe=False)
You can solve this by using safe=False:
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
return JsonResponse(posts, safe=False)
Note that it's not really unsafe - you just have to make sure on your own, that what you are trying to return can be converted to JSON.
See JsonResponse docs for reference.
Try to use values method: http://django.readthedocs.org/en/1.7.x/ref/models/querysets.html#django.db.models.query.QuerySet.values. It will produce dict-like representation for objects fields you need.
Related
I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:
from bson import ObjectId
async def get_single_template(db, template_id):
template = await db.templates.find_one({ '_id': ObjectId(template_id) })
return template
And I'm getting an error:
ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
"template_id" is a valid string, like "601401887ecf2f6153bbaaad". ObjectId created from it - too. It fails only to work inside find_one() method. When I'm using find() with that id it works well. I've tried from bson.objectid import ObjectId too - no difference. I'm using motor library to access mongo. Is there something that I'm missing?
P.S. Links to the corresponding docs:
https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-by-objectid
Though I'm using motor async library, I can't find direct examples in it's docs. Basically, it wraps pymongo. I can only find examples in other's source code.
Well, I've found out what caused that issue. The problem was not in the way I've tried to query data, but in the way I've tried to return it. I've forgotten to convert ObjectId to string in the entity that I've retrieved from database and tried to return it 'as is'. My bad.
I encountered this problem as well while using Python motor for Mongodb. In your app.collection.find_one(...), add {'_id': 0} along with the dictionary which has the value you want to search for.
So it should be like this:
await app.collection.find_one({"value": val},{'_id': 0})
After long research i find one solution work for me
I try many ways let's discuss with you one of them
DATABASE_URL = mongodb://localhost:portname/yourdbname
client = mongo_client.MongoClient(
settings.DATABASE_URL#, ServerSelectionTimeoutMS=5000
)
db = client[settings.MONGO_INITDB_DATABASE]
Post = db.post
#router.get('/')
async def posts(user_id: str = Depends(oauth2.require_user)):
list = []
for i in Post.find():
list.append(i)
print("list", list)
return {'status': 'success', "list": list}
Everything work on print but when i return the response then show me error that mentioned in post i solve this error by doing this
serialize ObjectId with native fastApi methods
at top of my file i just import
from bson.objectid import ObjectId
import pydantic
pydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
Note:
I am not expert of fastapi with MongoDB i just start learning last 5 days ago about fastapi and start learning mongoDb last 2 days ago. if you have any better practice then let me know
i also trying to serialize data but on that case also not work so try this way
thank you
this comment help me from github
https://github.com/tiangolo/fastapi/issues/1515#issuecomment-782838556
I am a programming self-learner and I am new to python and django and would like to optimize my code.
My problem is that I want to do a get_or_create with some loaded json data. Each dictionary entry is directly linked to my model. example:
data=json.load(file)
Person.objects.get_or_create(
firstname=data['firstname'],
surname=data['surname'],
gender=data['gender'],
datebirth=data['datebirth'],
)
Are there any ways to automatically link the json properties to my model fields instead of typing all my properties one by one?
What you might want to do is to unpack your list of arguments. Link to Python docs.
Say your model is Person:
p = Person(**data_dict)
p.save()
Reference
You need to write following code in python shell:
import json
data = json.loads(source)
print(json.dumps(data, indent=2))
I'm wondering if it's possible to correctly stream JSON in Django?
I've tried to use StreamingHTTPResponse but what I'm sending is incorrect JSON format - expected [json], sending [json][json]..[json], each is separate array.
I kind of understand the idea - we cannot send [json ... json... json]
because it will be incomplete on all iterations but last (it's important to close the array bracket). But maybe I'm wrong. Please help me to understand how JSON can be streamed correctly.
According to documentation StreamingHTTPResponse mostly used for csv, but nowhere is it said that it cannot be used for JSON. If that's the case, how to make it work?
Would really appreciate any help, I'm trying to solve this mystery for a few days now.
def generator_chunk():
...
yield df.to_json # returns data like [json]
#api_view(['GET'])
def return_data(request):
...
return StreamHttpResponse(generator_chunk) # streams data like [json][json], which is not proper json format
Similar questions (which have no answer):
Proper way of streaming JSON with Django
django stream a dictionary multiple times w/o breaking JSON
Here is some working code to send JSON stream with django:
from django.http import StreamingHttpResponse
def download_logs(self, request):
"""
:param request: Django HTTP Request
:return: Django HTTP Response
"""
def event_stream():
while True:
logs = self.retrieve_logs()
if len(logs) > 0:
yield f"data: {json.dumps(logs)}\n\n"
time.sleep(1)
return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
On the client side, you will need to parse the JSON string representation.
As you can probably tell from the nature of my question, I'm a little new to this. I have read similar post on this subject matter but most of it went right past my head and I did not feel like it was 100% applicable to the circumstance that I was facing so I thought I'd ask the question in a simplified way.
The question:
let's say I'm running the below HTMl form and a user submits the form to my views.py as shown in the views section below, I would able to store the value of the user selection by using: car_selection = request.POST.get('car') .
My question is, how would I be able to capture the HTML5 data of " data-animal-type="spider" " ?
I know there are Gurus out there but please do not explode my head. I would really need simplified help.
Thanks for helping.
Example HTML Form:
<select name="carlist" >
option data-car-type="premium" name= "car" value="audi">Audi</option>
</select>
Example Django View Function
def getcar(request):
...
if request.method == 'POST'
...
selected_carn = request.POST.get('car')
Well, it actually is possible. Say your view looks like this:
def getcar(request):
...
if request.method == 'POST'
myform = MyForm(request.POST)
...
myform includes uncleaned form in html. The you can use BeautifulSoup to extract data. Something like this:
from bs4 import BeautifulSoup
test = BeautifulSoup(str(myform))
data-values = [item["data-car-type"] for item in test.find_all() if "data-car-type" in item.attrs]
This will extract values from data-car-type attributes.
That being said, this does seem like a bad design. I surely would never go to such length to get the "car type" data. It's probably written somewhere in your database. Get it from there.
I know this question is 4 year old but I came across this page when a similar question arose in my mind.
Short answer
It's not possible, unless your use Javascript on the front end side as a workaround. The accepted answer is false.
Explanation
Indeed, in the example above, try to print(request.POST) and you'll see that the QueryDict object request.POST received by the view does not contain any reference to the HTML5 data attribute you want to fetch. It's basically a kind of Python dictionary (with a few distinctive features, cf. documentation). Admittedly, if you print(myform) in the same example, you'll see some HTML code. But, this code is generated retroactively, when you associate data with the form. Thus, BeautifulSoup will never be able to find what you're looking for. From the Django documentation:
If the form is submitted using a POST request, the view will [...] create a form instance and populate it with data from the
request: form = NameForm(request.POST). This is called “binding data to
the form” (it is now a bound form).
Workaround
What I've done on my side and what I would suggest you to do is to use some Javascript on the client side to add the missing information to the form when it's submitted. For instance, it could look like this:
document.querySelector("#form_id").addEventListener("submit", function(e) {
const your_data_attribute = document.getElementById("XXX").dataset.yourInfo;
const another_hidden_field = document.getElementById("YYY");
another_hidden_field.value = your_data_attribute;
});
I am trying to use Django with jquery UI autocomplete but having trouble sending response.
Here is my code:
def ajax_tags_autocomplete(request):
""" Autocomplete for tag list """
beginning_of_title = request.GET.get('term', '')
tags_found = Tag.objects.values_list('title', flat=True).filter(title__startswith=beginning_of_title)
return HttpResponse(json.dumps(tags_found), mimetype='application/json')
I get an error:
[u"php"] is not JSON serializable
Why? It is not possible to serialize a list? What should I pass to the serializer, then?
I would be greatful for any advice.
Are you sure it's actually a list containing unicode objects and not a list containing some database objects? The u"php" might just be the repr() of the object.
Try json.dumps([unicode(t) for t in tags_found]) or json.dumps(map(unicode, tags_found))