3👍
If I understand your question clearly then
Your view should be something like.
def add_comments(request):
if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE']:
print 'hi'
data = json.loads(request.body)
comment = data.get('comment')
id = data.get('id')
title = data.get('title')
post = Post.objects.get(id = id)
com = Comment()
com. comments = comment
com.title = post
com.save()
13👍
If you’re using Postgres, you can store json with JSONField
(read more), but if not, you need parse json to string and save with CharField
/TextField
using json.dumps(data)
. To recovery data, use json string to dict with json.loads(json_string)
Remember to import json lib: import json
Update 2023
Based on @Jarad comment,
JSONField is supported on MariaDB, MySQL, Oracle, PostgreSQL, and SQLite (with the JSON1 extension enabled).
https://docs.djangoproject.com/en/4.2/ref/models/fields/#jsonfield
- Django ALLOWED_HOSTS with ELB HealthCheck
- Django global variable
- Django form with fields from two different models
- How can I send signals from within Django migrations?
- Django templates stripping spaces?
8👍
Assuming a model of:
class User(models.Model):
name = models.CharField()
phone_number = models.CharField()
Sending json of {“name”:”Test User”, “phone_number”:”123-456-7890″}
In the view you could do the following to save it to the database.
def SaveUser(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
u = User(**body)
u.save()
return JsonResponse({"result": "OK"})
- Django prefetch_related's Prefetch, order_by?
- Django: How can I check the last activity time of user if user didn't log out?
- Google App Engine Application Extremely slow
- Unknown command: shell_plus and –settings
3👍
If you want to store the intact JSON, try using the django-jsonfield project: https://github.com/dmkoch/django-jsonfield
- Is there a way to make a block optional in Django template
- Django: WSGIRequest' object has no attribute 'user' on some pages?
- Order queryset by alternating value
- Access token from view
- Django-rest-framwork got AttributeError when attempting to get a value for field
0👍
according to Django doc you can use :
from django.contrib.postgres.fields import JSONField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = JSONField()
def __str__(self):
return self.name
then create with this :
Dog.objects.create(name='Rufus', data={
'breed': 'labrador',
'owner': {
'name': 'Bob',
'other_pets': [{
'name': 'Fishy',
}],
},
})
- Easy Way to Escape Django Template Variables
- Django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
- Attaching pdf's to emails in django